/// <summary> /// Verify that an action succeeds and produces a particular emulator command. /// </summary> /// <param name="session">Mock session.</param> /// <param name="del">Action to test.</param> /// <param name="expected">Expected text.</param> public static void VerifyCommand(this MockTaskSession session, VerifyDelegate del, string expected) { IoResult result; result = del(); Assert.AreEqual(true, result.Success); Assert.AreEqual(expected, session.LastCommandProcessed); }
/// <summary> /// Call this to End the asyncronous verification request. /// </summary> /// <param name="ar">The ar.</param> /// <returns></returns> public VerificationResult EndVerify(IAsyncResult ar) { VerifyDelegate verifyDelegate = ((AsyncResult)ar).AsyncDelegate as VerifyDelegate; if (verifyDelegate != null) { return(verifyDelegate.EndInvoke(ar)); } else { throw new InvalidOperationException("cannot get results, asynchresult is null"); } }
// This constructor will be used by NET45 for signing and for RSAKeyWrap internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hashAlgorithm, bool requirePrivateKey) { HashAlgorithm = hashAlgorithm; // RsaSecurityKey has either Rsa OR RsaParameters. // If we use the RsaParameters, we create a new RSA object and will need to dispose. if (key is RsaSecurityKey rsaKey) { InitializeUsingRsaSecurityKey(rsaKey, algorithm); } else if (key is X509SecurityKey x509Key) { InitializeUsingX509SecurityKey(x509Key, algorithm, requirePrivateKey); } else if (key is JsonWebKey jsonWebKey) { if (JsonWebKeyConverter.TryConvertToSecurityKey(jsonWebKey, out SecurityKey securityKey)) { if (securityKey is RsaSecurityKey rsaSecurityKeyFromJsonWebKey) { InitializeUsingRsaSecurityKey(rsaSecurityKeyFromJsonWebKey, algorithm); } else if (securityKey is X509SecurityKey x509SecurityKeyFromJsonWebKey) { InitializeUsingX509SecurityKey(x509SecurityKeyFromJsonWebKey, algorithm, requirePrivateKey); } else if (securityKey is ECDsaSecurityKey edcsaSecurityKeyFromJsonWebKey) { InitializeUsingEcdsaSecurityKey(edcsaSecurityKeyFromJsonWebKey); } else { throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10684, algorithm, key))); } } } else if (key is ECDsaSecurityKey ecdsaKey) { ECDsaSecurityKey = ecdsaKey; SignatureFunction = SignWithECDsa; VerifyFunction = VerifyWithECDsa; } else { throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10684, algorithm, key))); } }
public WorkflowManager() { InitializeComponent(); this.ApproveFn = ApprovePdf; this.VerifyFn = VerifyPdf; ShowNotifyIcon(); logfn = Log; string rootDir = Path.Combine(Application.StartupPath, "Portal"); webManager = new WebManager(rootDir, Properties.Settings.Default.WebManagerPort, this); webManager.SendLog = WebManagerLog; webManager.Start(); //string portal = Path.Combine(Application.StartupPath, "Portal\\index.html"); string portal = "http://localhost:" + Properties.Settings.Default.WebManagerPort.ToString() + "/index.html"; docDir = Path.Combine(Application.StartupPath, "Portal\\docs"); Process.Start(portal); }
/// <summary> /// Begins the verification in asynchronous mode. /// </summary> /// <param name="clientAETitle">The client AE title.</param> /// <param name="remoteAE">The remote AE.</param> /// <param name="remoteHost">The remote host.</param> /// <param name="remotePort">The remote port.</param> /// <param name="callback">The callback.</param> /// <param name="asyncState">State of the async.</param> /// <returns></returns> public IAsyncResult BeginVerify(string clientAETitle, string remoteAE, string remoteHost, int remotePort, AsyncCallback callback, object asyncState) { VerifyDelegate verifyDelegate = new VerifyDelegate(this.Verify); return(verifyDelegate.BeginInvoke(clientAETitle, remoteAE, remoteHost, remotePort, callback, asyncState)); }
private void InitializeUsingRsa(RSA rsa, string algorithm) { #if NET461 || NETSTANDARD2_0 if (algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256Signature, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384Signature, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512Signature, StringComparison.Ordinal)) { RSASignaturePadding = RSASignaturePadding.Pss; } else { // default RSASignaturePadding for other supported RSA algorithms is Pkcs1 RSASignaturePadding = RSASignaturePadding.Pkcs1; } #endif // This case is the result of a calling // X509Certificate2.GetPrivateKey OR X509Certificate2.GetPublicKey.Key // These calls return an AsymmetricAlgorithm which doesn't have API's to do much and need to be cast. // RSACryptoServiceProvider is wrapped to support SHA2 // RSACryptoServiceProviderProxy is only supported on Windows platform #if DESKTOP _useRSAOeapPadding = algorithm.Equals(SecurityAlgorithms.RsaOAEP, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap, StringComparison.Ordinal); if (rsa is RSACryptoServiceProvider rsaCryptoServiceProvider) { RsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(rsaCryptoServiceProvider); SignatureFunction = SignWithRsaCryptoServiceProviderProxy; VerifyFunction = VerifyWithRsaCryptoServiceProviderProxy; // RSACryptoServiceProviderProxy will keep track of if it creates a new RSA object. // Only if a new RSA was creaated, RSACryptoServiceProviderProxy will call RSA.Dispose(). _disposeCryptoOperators = true; return; } #endif // This case required the user to get a RSA object by calling // X509Certificate2.GetRSAPrivateKey() OR X509Certificate2.GetRSAPublicKey() // This requires 4.6+ to be installed. If a dependent library is targeting 4.5, 4.5.1, 4.5.2 or 4.6 // they will use Net45, but the type is RSACng. // The 'lightup' code will bind to the correct operators. #if NET45 else if (rsa.GetType().ToString().Equals(_rsaCngTypeName, StringComparison.Ordinal) && IsRsaCngSupported()) { _lightUpHashAlgorithmName = GetLightUpHashAlgorithmName(); SignatureFunction = Pkcs1SignData; VerifyFunction = Pkcs1VerifyData; return; } else { // In NET45 we only support RSACryptoServiceProvider or "System.Security.Cryptography.RSACng" throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10687, typeof(RSACryptoServiceProvider).ToString(), _rsaCngTypeName, rsa.GetType().ToString()))); } #endif #if NET461 || NETSTANDARD2_0 // Here we can use RSA straight up. _rsaEncryptionPadding = (algorithm.Equals(SecurityAlgorithms.RsaOAEP, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap, StringComparison.Ordinal)) ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1; RSA = rsa; SignatureFunction = SignWithRsa; VerifyFunction = VerifyWithRsa; #endif }
private void InitializeUsingEcdsaSecurityKey(ECDsaSecurityKey ecdsaSecurityKey) { ECDsaSecurityKey = ecdsaSecurityKey; SignatureFunction = SignWithECDsa; VerifyFunction = VerifyWithECDsa; }
/// <summary> /// Begins the verification in asynchronous mode. /// </summary> /// <param name="clientAETitle">The client AE title.</param> /// <param name="remoteAE">The remote AE.</param> /// <param name="remoteHost">The remote host.</param> /// <param name="remotePort">The remote port.</param> /// <param name="callback">The callback.</param> /// <param name="asyncState">State of the async.</param> /// <returns></returns> public IAsyncResult BeginVerify(string clientAETitle, string remoteAE, string remoteHost, int remotePort, AsyncCallback callback, object asyncState) { VerifyDelegate verifyDelegate = new VerifyDelegate(this.Verify); return verifyDelegate.BeginInvoke(clientAETitle, remoteAE, remoteHost, remotePort, callback, asyncState); }
/// <summary> /// Creates a new qryptext instance. <para> </para> /// Make sure to create one only once and cache it as needed, since loading the DLLs into memory can negatively affect the performance. /// <param name="sharedLibPathOverride">[OPTIONAL] Don't look for a <c>lib/</c> folder and directly use this path as a pre-resolved, platform-specific shared lib/DLL file path. Pass this if you want to manually handle the various platform's paths yourself.</param> /// </summary> public QryptextSharpContext(string sharedLibPathOverride = null) { string os; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { os = "windows"; loadUtils = new SharedLibLoadUtilsWindows(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { os = "linux"; loadUtils = new SharedLibLoadUtilsLinux(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { os = "mac"; loadUtils = new SharedLibLoadUtilsMac(); } else { throw new PlatformNotSupportedException("Unsupported OS"); } if (string.IsNullOrEmpty(sharedLibPathOverride)) { StringBuilder pathBuilder = new StringBuilder(256); pathBuilder.Append("lib/"); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X64: pathBuilder.Append("x64/"); break; case Architecture.X86: pathBuilder.Append("x86/"); break; case Architecture.Arm: pathBuilder.Append("armeabi-v7a/"); break; case Architecture.Arm64: pathBuilder.Append("arm64-v8a/"); break; } if (!Directory.Exists(pathBuilder.ToString())) { throw new PlatformNotSupportedException($"Qryptext shared library not found in {pathBuilder} and/or unsupported CPU architecture. Please don't forget to copy the Qryptext shared libraries/DLL into the 'lib/{{CPU_ARCHITECTURE}}/{{OS}}/{{SHARED_LIB_FILE}}' folder of your output build directory. https://github.com/GlitchedPolygons/qryptext/tree/master/csharp/lib/"); } pathBuilder.Append(os); pathBuilder.Append('/'); string[] l = Directory.GetFiles(pathBuilder.ToString()); if (l == null || l.Length != 1) { throw new FileLoadException("There should only be exactly one shared library file per supported platform!"); } pathBuilder.Append(Path.GetFileName(l[0])); LoadedLibraryPath = Path.GetFullPath(pathBuilder.ToString()); pathBuilder.Clear(); } else { LoadedLibraryPath = sharedLibPathOverride; } lib = loadUtils.LoadLibrary(LoadedLibraryPath); if (lib == IntPtr.Zero) { goto hell; } IntPtr enableFprintf = loadUtils.GetProcAddress(lib, "qryptext_enable_fprintf"); if (enableFprintf == IntPtr.Zero) { goto hell; } IntPtr disableFprintf = loadUtils.GetProcAddress(lib, "qryptext_disable_fprintf"); if (disableFprintf == IntPtr.Zero) { goto hell; } IntPtr isFprintfEnabled = loadUtils.GetProcAddress(lib, "qryptext_is_fprintf_enabled"); if (isFprintfEnabled == IntPtr.Zero) { goto hell; } IntPtr getVersionNumber = loadUtils.GetProcAddress(lib, "qryptext_get_version_number"); if (getVersionNumber == IntPtr.Zero) { goto hell; } IntPtr getVersionNumberString = loadUtils.GetProcAddress(lib, "qryptext_get_version_number_string"); if (getVersionNumberString == IntPtr.Zero) { goto hell; } IntPtr devUrandom = loadUtils.GetProcAddress(lib, "qryptext_dev_urandom"); if (devUrandom == IntPtr.Zero) { goto hell; } IntPtr calcEncryptionOutputLength = loadUtils.GetProcAddress(lib, "qryptext_calc_encryption_output_length"); if (calcEncryptionOutputLength == IntPtr.Zero) { goto hell; } IntPtr calcBase64Length = loadUtils.GetProcAddress(lib, "qryptext_calc_base64_length"); if (calcBase64Length == IntPtr.Zero) { goto hell; } IntPtr genKyber1K = loadUtils.GetProcAddress(lib, "qryptext_kyber1024_generate_keypair"); if (genKyber1K == IntPtr.Zero) { goto hell; } IntPtr genFalcon1K = loadUtils.GetProcAddress(lib, "qryptext_falcon1024_generate_keypair"); if (genFalcon1K == IntPtr.Zero) { goto hell; } IntPtr encrypt = loadUtils.GetProcAddress(lib, "qryptext_encrypt"); if (encrypt == IntPtr.Zero) { goto hell; } IntPtr decrypt = loadUtils.GetProcAddress(lib, "qryptext_decrypt"); if (decrypt == IntPtr.Zero) { goto hell; } IntPtr sign = loadUtils.GetProcAddress(lib, "qryptext_sign"); if (sign == IntPtr.Zero) { goto hell; } IntPtr verify = loadUtils.GetProcAddress(lib, "qryptext_verify"); if (verify == IntPtr.Zero) { goto hell; } enableFprintfDelegate = Marshal.GetDelegateForFunctionPointer <EnableFprintfDelegate>(enableFprintf); disableFprintfDelegate = Marshal.GetDelegateForFunctionPointer <DisableFprintfDelegate>(disableFprintf); isFprintfEnabledDelegate = Marshal.GetDelegateForFunctionPointer <IsFprintfEnabledDelegate>(isFprintfEnabled); getVersionNumberDelegate = Marshal.GetDelegateForFunctionPointer <GetVersionNumberDelegate>(getVersionNumber); getVersionNumberStringDelegate = Marshal.GetDelegateForFunctionPointer <GetVersionNumberStringDelegate>(getVersionNumberString); devUrandomDelegate = Marshal.GetDelegateForFunctionPointer <DevUrandomDelegate>(devUrandom); calcEncryptionOutputLengthDelegate = Marshal.GetDelegateForFunctionPointer <CalcEncryptionOutputLengthDelegate>(calcEncryptionOutputLength); calcBase64LengthDelegate = Marshal.GetDelegateForFunctionPointer <CalcBase64LengthDelegate>(calcBase64Length); generateKyber1024KeyPairDelegate = Marshal.GetDelegateForFunctionPointer <GenerateKyber1024KeyPairDelegate>(genKyber1K); generateFalcon1024KeyPairDelegate = Marshal.GetDelegateForFunctionPointer <GenerateFalcon1024KeyPairDelegate>(genFalcon1K); encryptDelegate = Marshal.GetDelegateForFunctionPointer <EncryptDelegate>(encrypt); decryptDelegate = Marshal.GetDelegateForFunctionPointer <DecryptDelegate>(decrypt); signDelegate = Marshal.GetDelegateForFunctionPointer <SignDelegate>(sign); verifyDelegate = Marshal.GetDelegateForFunctionPointer <VerifyDelegate>(verify); return; hell: throw new Exception($"Failed to load one or more functions from the shared library \"{LoadedLibraryPath}\"!"); }
private void InitializeUsingRsa(RSA rsa, string algorithm) { // The return value for X509Certificate2.GetPrivateKey OR X509Certificate2.GetPublicKey.Key is a RSACryptoServiceProvider // These calls return an AsymmetricAlgorithm which doesn't have API's to do much and need to be cast. // RSACryptoServiceProvider is wrapped with RSACryptoServiceProviderProxy as some CryptoServideProviders (CSP's) do // not natively support SHA2. #if DESKTOP if (rsa is RSACryptoServiceProvider rsaCryptoServiceProvider) { _useRSAOeapPadding = algorithm.Equals(SecurityAlgorithms.RsaOAEP) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap); RsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(rsaCryptoServiceProvider); DecryptFunction = DecryptWithRsaCryptoServiceProviderProxy; EncryptFunction = EncryptWithRsaCryptoServiceProviderProxy; SignatureFunction = SignWithRsaCryptoServiceProviderProxy; VerifyFunction = VerifyWithRsaCryptoServiceProviderProxy; // RSACryptoServiceProviderProxy will track if a new RSA object is created and dispose appropriately. _disposeCryptoOperators = true; return; } #endif #if NET45 // This case required the user to get a RSA object by calling // X509Certificate2.GetRSAPrivateKey() OR X509Certificate2.GetRSAPublicKey() // This requires 4.6+ to be installed. If a dependent library is targeting 4.5, 4.5.1, 4.5.2 or 4.6 // they will bind to our Net45 target, but the type is RSACng. // The 'lightup' code will bind to the correct operators. else if (rsa.GetType().ToString().Equals(_rsaCngTypeName) && IsRsaCngSupported()) { _useRSAOeapPadding = algorithm.Equals(SecurityAlgorithms.RsaOAEP) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap); _lightUpHashAlgorithmName = GetLightUpHashAlgorithmName(); DecryptFunction = DecryptNet45; EncryptFunction = EncryptNet45; SignatureFunction = Pkcs1SignData; VerifyFunction = Pkcs1VerifyData; RSA = rsa; return; } else { // In NET45 we only support RSACryptoServiceProvider or "System.Security.Cryptography.RSACng" throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10687, LogHelper.MarkAsNonPII(typeof(RSACryptoServiceProvider).ToString()), LogHelper.MarkAsNonPII(_rsaCngTypeName), LogHelper.MarkAsNonPII(rsa.GetType().ToString())))); } #endif #if NET461 || NET472 || NETSTANDARD2_0 if (algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256Signature) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384Signature) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512) || algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512Signature)) { RSASignaturePadding = RSASignaturePadding.Pss; } else { // default RSASignaturePadding for other supported RSA algorithms is Pkcs1 RSASignaturePadding = RSASignaturePadding.Pkcs1; } RSAEncryptionPadding = (algorithm.Equals(SecurityAlgorithms.RsaOAEP) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap)) ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1; RSA = rsa; DecryptFunction = DecryptWithRsa; EncryptFunction = EncryptWithRsa; SignatureFunction = SignWithRsa; VerifyFunction = VerifyWithRsa; #endif }
public VerifierAttribute(Type typeContainingMethod, string methodName) { Handler = (VerifyDelegate)Delegate.CreateDelegate( typeof(VerifyDelegate), typeContainingMethod.GetMethod(methodName)); }
public OrlpEd25519Context(string sharedLibPathOverride = null) { string os; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { os = "windows"; loadUtils = new SharedLibLoadUtilsWindows(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { os = "linux"; loadUtils = new SharedLibLoadUtilsLinux(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { os = "mac"; loadUtils = new SharedLibLoadUtilsMac(); } else { throw new PlatformNotSupportedException("Unsupported OS"); } if (!string.IsNullOrEmpty(sharedLibPathOverride)) { LoadedLibraryPath = sharedLibPathOverride; } else { string cpu = RuntimeInformation.ProcessArchitecture switch { Architecture.X64 => "x64", Architecture.X86 => "x86", Architecture.Arm => "armeabi-v7a", Architecture.Arm64 => "arm64-v8a", _ => throw new PlatformNotSupportedException("CPU Architecture not supported!") }; string path = Path.Combine(Path.GetFullPath(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) ?? "."), "lib", cpu, os); if (!Directory.Exists(path)) { throw new PlatformNotSupportedException($"Shared library not found in {path} and/or unsupported CPU architecture. Please don't forget to copy the shared libraries/DLL into the 'lib/{{CPU_ARCHITECTURE}}/{{OS}}/{{SHARED_LIB_FILE}}' folder of your output build directory. "); } bool found = false; foreach (string file in Directory.GetFiles(path)) { if (file.ToLower().Contains("ed25519")) { LoadedLibraryPath = Path.GetFullPath(Path.Combine(path, file)); found = true; break; } } if (!found) { throw new FileLoadException($"Shared library not found in {path} and/or unsupported CPU architecture. Please don't forget to copy the shared libraries/DLL into the 'lib/{{CPU_ARCHITECTURE}}/{{OS}}/{{SHARED_LIB_FILE}}' folder of your output build directory. "); } } lib = loadUtils.LoadLibrary(LoadedLibraryPath); if (lib == IntPtr.Zero) { goto hell; // The gates of hell opened, and out came the beginning of marshalling, DLL hell and C# interop... } IntPtr createSeed = loadUtils.GetProcAddress(lib, "ed25519_create_seed"); if (createSeed == IntPtr.Zero) { goto hell; } IntPtr createKeypair = loadUtils.GetProcAddress(lib, "ed25519_create_keypair"); if (createKeypair == IntPtr.Zero) { goto hell; } IntPtr sign = loadUtils.GetProcAddress(lib, "ed25519_sign"); if (sign == IntPtr.Zero) { goto hell; } IntPtr verify = loadUtils.GetProcAddress(lib, "ed25519_verify"); if (verify == IntPtr.Zero) { goto hell; } IntPtr addScalar = loadUtils.GetProcAddress(lib, "ed25519_add_scalar"); if (addScalar == IntPtr.Zero) { goto hell; } IntPtr keyExchange = loadUtils.GetProcAddress(lib, "ed25519_key_exchange"); if (keyExchange == IntPtr.Zero) { goto hell; } IntPtr keyConvert = loadUtils.GetProcAddress(lib, "ed25519_key_convert_ref10_to_orlp"); if (keyConvert == IntPtr.Zero) { goto hell; } createSeedDelegate = Marshal.GetDelegateForFunctionPointer <CreateSeedDelegate>(createSeed); createKeypairDelegate = Marshal.GetDelegateForFunctionPointer <CreateKeypairDelegate>(createKeypair); signDelegate = Marshal.GetDelegateForFunctionPointer <SignDelegate>(sign); verifyDelegate = Marshal.GetDelegateForFunctionPointer <VerifyDelegate>(verify); addScalarDelegate = Marshal.GetDelegateForFunctionPointer <AddScalarDelegate>(addScalar); keyExchangeDelegate = Marshal.GetDelegateForFunctionPointer <KeyExchangeDelegate>(keyExchange); ref10KeyConversionDelegate = Marshal.GetDelegateForFunctionPointer <Ref10KeyConversionDelegate>(keyConvert); return; hell: throw new Exception($"Failed to load one or more functions from the orlp-ed25519 shared library \"{LoadedLibraryPath}\"!"); }