Ejemplo n.º 1
0
        public static bool Decrypt(string p_strSrc, out string p_strOut)
        {
            p_strOut = "";
            bool bRet = false;

            if (m_hDllHandle == IntPtr.Zero)
            {
                p_strOut = p_strSrc;
                return(false);
            }

            lock (typeof(EncryptApi))
            {
                IntPtr          pFunc = GetProcAddress(m_hDllHandle, "Decrypt");
                DecryptDelegate d     = (DecryptDelegate)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(DecryptDelegate));
                IntPtr          pRet  = d(p_strSrc);
                if (pRet == IntPtr.Zero)
                {
                    p_strOut = p_strSrc;
                    bRet     = false;
                }
                else
                {
                    p_strOut = Marshal.PtrToStringAnsi(pRet);
                    bRet     = true;
                }
            }

            return(bRet);
        }
Ejemplo n.º 2
0
        public bool LoadUnmanagedDll(string dll)
        {
            int hModule = DLLManager.LoadLibrary(dll);

            if (hModule == 0)
            {
                int err = Marshal.GetLastWin32Error();
                Console.WriteLine("LoadLibrary Failed for {0} code ({1}): {2}", dll, err, new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return(false);
            }
            Console.WriteLine("LoadLibrary Success.");
            dll_init = DLLManager.GetProcAddress(hModule, "init");
            if (dll_init == IntPtr.Zero)
            {
                Console.WriteLine("Unable to find the address of init");
                return(false);
            }

            DecryptorInit = (DecryptInitDelegate)Marshal.GetDelegateForFunctionPointer(dll_init, typeof(DecryptInitDelegate));
            if (DecryptorInit == null)
            {
                Console.WriteLine("decrypt's init() failed to be found!");
                return(false);
            }
            Console.WriteLine("GetProcAddress of init() success.");
            dll_decrypt = DLLManager.GetProcAddress(hModule, "decrypt");
            if (dll_decrypt == IntPtr.Zero)
            {
                Console.WriteLine("Unable to find the address of decrypt!");
                return(false);
            }
            Console.WriteLine("GetProcAddress of decrypt() success.");
            DecryptorDecrypt = (DecryptDelegate)Marshal.GetDelegateForFunctionPointer(dll_decrypt, typeof(DecryptDelegate));

            if (DecryptorDecrypt == null)
            {
                Console.WriteLine("Decryptor function is null!");
                return(false);
            }
            Console.WriteLine("{0} decryption dll successfully loaded!\n", dll);
            return(true);
        }
        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, StringComparison.Ordinal) ||
                                     algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap, StringComparison.Ordinal);

                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, StringComparison.Ordinal) && IsRsaCngSupported())
            {
                _useRSAOeapPadding = algorithm.Equals(SecurityAlgorithms.RsaOAEP, StringComparison.Ordinal) ||
                                     algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap, StringComparison.Ordinal);

                _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, typeof(RSACryptoServiceProvider).ToString(), _rsaCngTypeName, rsa.GetType().ToString())));
            }
#endif

#if NET461 || NET472 || 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;
            }

            RSAEncryptionPadding = (algorithm.Equals(SecurityAlgorithms.RsaOAEP, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap, StringComparison.Ordinal))
                        ? RSAEncryptionPadding.OaepSHA1
                        : RSAEncryptionPadding.Pkcs1;
            RSA               = rsa;
            DecryptFunction   = DecryptWithRsa;
            EncryptFunction   = EncryptWithRsa;
            SignatureFunction = SignWithRsa;
            VerifyFunction    = VerifyWithRsa;
#endif
        }
Ejemplo n.º 4
0
        /// <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}\"!");
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a new pwcrypt 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 handle the various platform's paths yourself.</param>
        /// </summary>
        public PwcryptSharpContext(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("pwcrypt"))
                    {
                        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;
            }

            IntPtr enableFprintf = loadUtils.GetProcAddress(lib, "pwcrypt_enable_fprintf");

            if (enableFprintf == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr disableFprintf = loadUtils.GetProcAddress(lib, "pwcrypt_disable_fprintf");

            if (disableFprintf == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr isFprintfEnabled = loadUtils.GetProcAddress(lib, "pwcrypt_is_fprintf_enabled");

            if (isFprintfEnabled == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr getVersionNumber = loadUtils.GetProcAddress(lib, "pwcrypt_get_version_nr");

            if (getVersionNumber == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr getVersionNumberString = loadUtils.GetProcAddress(lib, "pwcrypt_get_version_nr_string");

            if (getVersionNumberString == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr getArgon2VersionNumber = loadUtils.GetProcAddress(lib, "pwcrypt_get_argon2_version_nr");

            if (getArgon2VersionNumber == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr devUrandom = loadUtils.GetProcAddress(lib, "dev_urandom");

            if (devUrandom == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr getFilesize = loadUtils.GetProcAddress(lib, "pwcrypt_get_filesize");

            if (getFilesize == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr assessPasswordStrength = loadUtils.GetProcAddress(lib, "pwcrypt_assess_password_strength");

            if (assessPasswordStrength == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr encrypt = loadUtils.GetProcAddress(lib, "pwcrypt_encrypt");

            if (encrypt == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr decrypt = loadUtils.GetProcAddress(lib, "pwcrypt_decrypt");

            if (decrypt == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr free = loadUtils.GetProcAddress(lib, "pwcrypt_free");

            if (free == 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);
            getArgon2VersionNumberDelegate = Marshal.GetDelegateForFunctionPointer <GetArgon2VersionNumberDelegate>(getArgon2VersionNumber);
            devUrandomDelegate             = Marshal.GetDelegateForFunctionPointer <DevUrandomDelegate>(devUrandom);
            getFilesizeDelegate            = Marshal.GetDelegateForFunctionPointer <GetFilesizeDelegate>(getFilesize);
            assessPasswordStrengthDelegate = Marshal.GetDelegateForFunctionPointer <AssessPasswordStrengthDelegate>(assessPasswordStrength);
            encryptDelegate = Marshal.GetDelegateForFunctionPointer <EncryptDelegate>(encrypt);
            decryptDelegate = Marshal.GetDelegateForFunctionPointer <DecryptDelegate>(decrypt);
            freeDelegate    = Marshal.GetDelegateForFunctionPointer <FreeDelegate>(free);

            return;

hell:
            throw new Exception($"Failed to load one or more functions from the shared library \"{LoadedLibraryPath}\"!");
        }