src/_Internals/CryptoManager.ps1


$CryptoHashAlgorythm = "SHA1";
$CryptoInitVector = "ahC3@bCa2Didfc3d";
$CryptoKeySize = 256;
$CryptoPassPhrase = "MsCrmTools";
$CryptoPasswordIterations = 2;
$CryptoSaltValue = "Tanguy 92*";

function Repair-XrbConnectionString {
    PARAM(
        [Parameter(Mandatory = $True)]
        [string]
        [ValidateNotNullOrEmpty()]
        $ConnectionString
    )

    # Parsed as the SDK reads it, then written back with the clear value quoted when it needs it (S3): a String.Replace
    # of the encrypted text could also change another part of the string, and a clear value with ';' broke it
    $parameters = ConvertTo-XrmConnectionStringMapInternal -RawConnectionString $ConnectionString;
    foreach ($parameterKey in @("password", "clientsecret", "secret")) {
        if (-not $parameters.Contains($parameterKey)) {
            continue;
        }
        $encryptedText = $parameters[$parameterKey].Value;
        if ([String]::IsNullOrWhiteSpace($encryptedText)) {
            continue;
        }

        # Weird case : remove "..." added by XTB
        if ($encryptedText.StartsWith('"') -and $encryptedText.EndsWith('"')) {
            $encryptedText = $encryptedText.Trim('"');
        }

        $parameters[$parameterKey].Value = Unprotect-XrmToolBoxPassword -EncryptedPassword $encryptedText;
        return (ConvertFrom-XrmConnectionStringMapInternal -Parameters $parameters);
    }

    throw "ConnectionString is not encrypted!";
}

function Protect-XrmToolBoxPassword {
    PARAM(
        [Parameter(Mandatory = $True)]
        [string]
        [ValidateNotNullOrEmpty()]
        $Password
    )

    $initVectorBytes = [System.Text.Encoding]::ASCII.GetBytes($CryptoInitVector);
    $saltValueBytes = [System.Text.Encoding]::ASCII.GetBytes($CryptoSaltValue);
    $plainTextBytes = [System.Text.Encoding]::UTF8.GetBytes($Password);

    $passwordBytes = new-object "System.Security.Cryptography.PasswordDeriveBytes" -ArgumentList $CryptoPassPhrase, $saltValueBytes, $CryptoHashAlgorythm, $CryptoPasswordIterations;
    $keyBytes = $passwordBytes.GetBytes($CryptoKeySize / 8);

    $symmetricKey = new-object "System.Security.Cryptography.RijndaelManaged";
    $symmetricKey.Mode = [System.Security.Cryptography.CipherMode]::CBC;
    $encryptor = $symmetricKey.CreateEncryptor($keyBytes, $initVectorBytes);

    $memoryStream = new-object "System.IO.MemoryStream";
    $cryptoStreamMode = [System.Security.Cryptography.CryptoStreamMode]::Write;
    $cryptoStream = new-object "System.Security.Cryptography.CryptoStream" -ArgumentList $memoryStream, $encryptor, $cryptoStreamMode;
    $cryptoStream.Write($plainTextBytes, 0, $plainTextBytes.Length);
    $cryptoStream.FlushFinalBlock() | Out-Null;

    $cipherTextBytes = $memoryStream.ToArray();

    $memoryStream.Close() | Out-Null;
    $cryptoStream.Close() | Out-Null;

    $cipherText = [Convert]::ToBase64String($cipherTextBytes);

    return $cipherText;
}

function Unprotect-XrmToolBoxPassword {
    PARAM(
        [Parameter(Mandatory = $True)]
        [string]
        [ValidateNotNullOrEmpty()]
        $EncryptedPassword
    )

    $initVectorBytes = [System.Text.Encoding]::ASCII.GetBytes($CryptoInitVector);
    $saltValueBytes = [System.Text.Encoding]::ASCII.GetBytes($CryptoSaltValue);
    $cipherBytes = [Convert]::FromBase64String($EncryptedPassword);
    $passwordBytes = new-object "System.Security.Cryptography.PasswordDeriveBytes" -ArgumentList $CryptoPassPhrase, $saltValueBytes, $CryptoHashAlgorythm, $CryptoPasswordIterations;
    $keyBytes = $passwordBytes.GetBytes($CryptoKeySize / 8);
    
    $symmetricKey = new-object "System.Security.Cryptography.RijndaelManaged";
    $symmetricKey.Mode = [System.Security.Cryptography.CipherMode]::CBC;
    $decryptor = $symmetricKey.CreateDecryptor($keyBytes, $initVectorBytes);

    $memoryStream = new-object "System.IO.MemoryStream" -ArgumentList (, $cipherBytes);
    $cryptoStreamMode = [System.Security.Cryptography.CryptoStreamMode]::Read;
    $cryptoStream = new-object "System.Security.Cryptography.CryptoStream" -ArgumentList $memoryStream, $decryptor, $cryptoStreamMode;
    
    # Read to the end: since .NET 6, one Read call may return a part of the content only
    $clearTextStream = new-object "System.IO.MemoryStream";
    $cryptoStream.CopyTo($clearTextStream);
    $clearTextBytes = $clearTextStream.ToArray();

    $clearTextStream.Close() | Out-Null;
    $memoryStream.Close() | Out-Null;
    $cryptoStream.Close() | Out-Null;

    $clearText = [System.Text.Encoding]::UTF8.GetString($clearTextBytes);

    return $clearText;
}