How to decode an encrypted standard string

156 views Asked by At

I'm transforming a string into an encrypted standard string in PowerShell, then I'd like to use C# to retrieve this encrypted standard string and transform it back into a plain string, in order to use it as a password.

Thank you for your help. Sincerely, Maxime

Here's my PowerShell code :

$pwd = Read-Host -Prompt "Entrez le mot de passe" 
$securePwd = ConvertTo-SecureString $pwd -AsPlainText -Force 
$encryptedPwd = ConvertFrom-SecureString -SecureString $securePwd -Key (1..16) 
$encryptedPwd | Out-File -FilePath $svcAccountPath 

Here's my C# code :

static SecureString DecryptPassword(byte[] key, string filePath)
        {
            byte[] encryptedData = File.ReadAllBytes(filePath);
            byte[] decryptedData = ProtectedData.Unprotect(encryptedData, key, DataProtectionScope.CurrentUser);

            SecureString decryptedPassword = new SecureString();
            foreach (byte b in decryptedData)
            {
                decryptedPassword.AppendChar((char)b);
            }

            return decryptedPassword;
        }
        static string DecryptSecureString(SecureString secureString)
        {
            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
        private void idk()
        {
            string pwdSeduredFile = "C:/Temp/C01 User Manager/conf/encryptedPwd.txt";
            byte[] key = new byte[16];
            for (int i = 0; i < 16; i++)
            {
                key[i] = (byte)(i + 1);
            }
            SecureString encryptedPassword = DecryptPassword(key, pwdSeduredFile);
            string password1 = DecryptSecureString(encryptedPassword);
            MessageBox.Show("password :" + password1, "Erreur", MessageBoxButton.OK, MessageBoxImage.Information);
        }

I have an error on the ligne "byte[] decryptedData = ProtectedData.Unprotect(encryptedData, key, DataProtectionScope.CurrentUser);" I attach it to this message.

0

There are 0 answers