Key not valid for use in specified state

Rising Flight 4,556 Reputation points
2024-10-13T19:58:38.32+00:00

I have using an Azure App Registration and i have encrypted client secret using the below syntax from powershell.

$myfile = 'c:\temp\myappreg.key'
Read-Host -assecurestring | convertfrom-securestring | out-file $myfile

I am using below lines in the script and i am getting error.Key not valid for use in specified state.

$ClientId = "9999999999999999999"
$ClientKeyPath = "c:\temp\myappreg.key"
$TenantId = "88888888888888888888888""
# Read the encrypted client secret from the file and convert it back to a secure string
$SecureString = Get-Content $ClientKeyPath | ConvertTo-SecureString
# Convert the secure string to plain text
$ClientSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
)
# Get an access token
$body = @{
    grant_type    = "client_credentials"
    client_id     = $ClientId
    client_secret = $ClientSecret
    scope         = "https://outlook.office365.com/.default"
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $response.access_token
# Load EWS Managed API (Exchange 2016)
$EWSServicePath = 'C:\EWS\bin\Debug\Microsoft.Exchange.WebServices.dll'
Import-Module $EWSServicePath
 
# Connect to Exchange Online using EWS with OAuth
$ExchVer = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2016
$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchVer)
$Service.Url = "https://outlook.office365.com/EWS/Exchange.asmx"
$Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCredentials($accessToken)
==========================================================================================


I am getting below error

Error
At line:9 char:46
+ $SecureString = Get-Content $ClientKeyPath | ConvertTo-SecureString
+                                              ~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
    + FullyQualifiedErrorId : 
ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
ConvertTo-SecureString : Key not valid for use in specified state.
At line:9 char:46
+ $SecureString = Get-Content $ClientKeyPath | ConvertTo-SecureString
+                                              ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
    + FullyQualifiedErrorId : ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
Exception calling "SecureStringToBSTR" with "1" argument(s): "Value cannot be null.
Parameter name: s"
At line:12 char:1
+ $ClientSecret = [System.Runtime.InteropServices.Marshal]::PtrToString ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException
Exception calling "SecureStringToBSTR" with "1" argument(s): "Value cannot be null.
Parameter name: s"
At line:12 char:1
+ $ClientSecret = [System.Runtime.InteropServices.Marshal]::PtrToString ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException


Microsoft Exchange Online
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,056 questions
Microsoft Exchange Online Management
Microsoft Exchange Online Management
Microsoft Exchange Online: A Microsoft email and calendaring hosted service.Management: The act or process of organizing, handling, directing or controlling something.
4,536 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,530 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce Jing-MSFT 5,030 Reputation points Microsoft Vendor
    2024-10-14T05:26:21.0433333+00:00

    Hi,@Rising Flight

    Thanks for posting your question in the Microsoft Q&A forum.

    The error message you're receiving indicates that there is a problem with the way the secure string is being handled. The ConvertTo-SecureString cmdlet is throwing an error because it cannot decrypt the content of the file specified by $ClientKeyPath. This can happen if the secure string was encrypted by a different user or on a different machine than the one trying to decrypt it, because by default, ConvertTo-SecureString uses the Windows Data Protection API (DPAPI) which is specific to both the user and the machine.

    To resolve this issue, you need to ensure that the secure string is being encrypted and decrypted by the same user on the same machine. If the secure string was encrypted with a key, you need to use the same key to decrypt it.

    If my answer is helpful to you, please mark it as the answer so that other users can refer to it. Thank you for your support and understanding.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.