The below will be what you are looking for, to encrypt a string for use later as a password:
##############################################################################
#.SYNOPSIS
# Encrypts a password with a randomly generated AES Key
#
#
#.DESCRIPTION
# Outputs a file with the AES key in and a file with the encrypted password in. If you set ACL on the AES Key File, no one else can decrypt your password
#
#
#.PARAMETER AESKeyFilePath
# File path to store the AES key
#
#
#.PARAMETER PasswordToEncrypt
# Plain text password to encrypt
#
#
#.PARAMETER CredentialFilePath
# File path to store the encrypted password
#
#
#.EXAMPLE
# EncryptWith-AesKey "C:\AESKeyFilePath.txt" "SomeRandomPassword1!" "C:\CredentialFilePath.txt"
##############################################################################
function EncryptWith-AesKey($AESKeyFilePath, $PasswordToEncrypt, $CredentialFilePath) {
# Generate a random AES Encryption Key.
$AESKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)
# Store the AESKey into a file. This file should be protected! (e.g. ACL on the file to allow only select people to read)
Set-Content $AESKeyFilePath $AESKey # Any existing AES Key file will be overwritten
# Store password that has been encrypted with the AESKey
$password = $PasswordToEncrypt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -Key $AESKey
Set-Content $credentialFilePath $password
}
Set paths for AES encryption key and encrypted password, then enter password to encrypt into the read-host prompt:
$AESFP = "C:\aes\aes"
$Password = Read-Host "Please enter new password to encrypt, this will overwrite current password:"
$CredFP = "C:\enc\pwd"
Run function to encrypt password and write it to $CredFP file.
EncryptWith-AesKey $AESFP $Password $CredFP
#Decrypt password as a secure string (unreadable by user)
$AESKey = Get-Content "C:\aes\AES"
$pwdTxt = Get-Content "C:\enc\pwn"
$securePwd = $pwdTxt | ConvertTo-SecureString -Key $AESKey
Cred object (to pass to -Credential or -Credentials)
$CredObject = New-Object System.Management.Automation.PSCredential -ArgumentList "My.Username@My-Company.com", $securePwd
Username and Password (not visible to user) if need separately:
$Username = $CredObject.UserName
$Password = $CredObject.Password
So for your Sharepoint connection:
Connect-SPOService -Url https://tenant-admin.sharepoint.com -Credential $CredObject
Hope this helps! Bit late I know.