ProtectStrings.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
### --- PUBLIC FUNCTIONS --- ###
#Region - Export-MasterPassword.ps1
Function Export-MasterPassword {
    <#
    .Synopsis
    Export the currently set Master Password to a text file
    .Description
    Function to retrieve the currently set master password and export it to a text file for transportation between systems or backup.
    Similar in end result to generating an AES key and saving it to file.
    .Parameter FilePath
    Destination full path (including file name) for exported AES Key.
    .EXAMPLE
    PS C:\> Export-MasterPassword -FilePath C:\temp\keyfile.txt
 
 
    this will convert the current session AES key from a SecureString object to its raw byte values, encode in Base64
    and export it to a file called keyfile.txt
    .NOTES
    Version: 1.0
    Author: C. Bodett
    Creation Date: 3/28/2022
    Purpose/Change: Initial function development
    #>

    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [validatescript({
            if( -not ($_.DirectoryName | test-path) ){
                throw "Folder does not exist"
                }
                return $true
        })]
        [Alias('Path')]
        [System.IO.FileInfo]$FilePath
    )

    Begin {
        $SecureAESKey = Try {
            $Global:AESMP
        } Catch {
            # do nothing
        }
    }

    Process {
        if ($SecureAESKey) {
            Write-Verbose "Stored AES key found"
            $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey
            Write-Verbose "Converting to Base64 before export"
            $EncodedKey = ConvertTo-Base64 -TextString $ClearTextAESKey
            Write-Verbose "Saving to $Filepath with Encoded key:"
            Write-Debug "$EncodedKey"
            Out-File -FilePath $FilePath -InputObject $EncodedKey -Force
        } else {
            Write-Warning "No key found to export"
        }
    }

}
#Region - Get-MasterPassword.ps1
Function Get-MasterPassword {
    <#
    .Synopsis
    Returns the saved MasterPassword derived key.
    .Description
    This function is mostly used to verify that a MasterPassword is currently stored. It returns a SecureString object with the current stored AES key.
    .EXAMPLE
    PS C:\> Get-MasterPassword
 
    does stuff
    .NOTES
    Version: 1.0
    Author: C. Bodett
    Creation Date: 3/28/2022
    Purpose/Change: Initial function development
    #>

    [cmdletbinding()]
    Param (
        [Switch]$Boolean
    )
    Write-Verbose "Checking for stored AES key"

    if ($Boolean) {
        Get-AESMPVariable -Boolean
    } else {
        Get-AESMPVariable
    }

}
#Region - Import-MasterPassword.ps1
Function Import-MasterPassword {
    <#
    .Synopsis
    Import a previously exported master password from a text file
    .Description
    Function to import a previously exported master password keyfile and save it in the current session as the master password.
    .Parameter FilePath
    Destination full path (including file name) for the file containing the exported AES Key.
    .EXAMPLE
    PS C:\> Import-MasterPassword -FilePath C:\temp\keyfile.txt
 
 
    This will important the key from keyfile.txt and store it in the current Powershell session as the Master Password.
    .NOTES
    Version: 1.0
    Author: C. Bodett
    Creation Date: 3/28/2022
    Purpose/Change: Initial function development
    #>

    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [validatescript({
            if( -not ($_ | test-path) ){
                throw "File does not exist"
                }
            if(-not ( $_ | test-path -PathType Leaf) ){
                throw "The -FilePath argument must be a file"
                }
                return $true
        })]
        [Alias('Path')]
        [System.IO.FileInfo]$FilePath
    )

    Begin {
        Try {
            Write-Verbose "Retreiving file content from: $FilePath"
            $EncodedKey = Get-Content -Path $FilePath -ErrorAction Stop
        } Catch {
            Write-Error $_
        }
    }

    Process {
        If ($EncodedKey) {
            $ClearTextAESKey = ConvertFrom-Base64 -TextString $EncodedKey
            Write-Verbose "Storing AES Key to current session"
            $SecureAESKey = ConvertTo-SecureString -String $ClearTextAESKey -AsPlainText -Force
            Set-AESMPVariable -MPKey $SecureAESKey
        }
    }

}
#Region - Protect-String.ps1
Function Protect-String {
    <#
    .Synopsis
    Encrypt a provided string with DPAPI or AES 256-bit encryption and return the cipher text.
    .Description
    This function will encrypt provided string text with either Microsoft's DPAPI or AES 256-bit encryption. By default it will use DPAPI unless specified.
    Returns a string object of Base64 encoded text.
    .Parameter InputString
    This is the string text you wish to protect with encryption. Can be provided via the pipeline.
    .Parameter Encryption
    Specify either DPAPI or AES encryption. DPAPI is the default if not specified.
    .EXAMPLE
    PS C:\> Protect-String "Secret message"
    eyJFbmNyeXB0aW9uIjoiRFBBUEkiLCJDaXBoZXJUZXh0IjoiMDEwMDAwMDBkMDhjOWRkZjAxMTVkMTExOGM3YTAwYzA0ZmMyOTdlYjAxMDAwMDAwODRkMTVhY2QwZjk5ZDM0NDllNzE5MTkwZGI0YzY2ZWUwMDAwMDAwMDAyMDAwMDAwMDAwMDAzNjYwMDAwYzAwMDAwMDAxMDAwMDAwMGMyNjFhZTY5YThjZjdlMTI0ZTJmZWI3MmVmMTk3YmRlMDAwMDAwMDAwNDgwMDAwMGEwMDAwMDAwMTAwMDAwMDA4NjUxZWJjZWY4MTE4MzEzMzljNDMyNjA5OWUxZWY3ZDIwMDAwMDAwZGQ3MDUyNGFkZGZlMmM5YzQyMDlhZDc2NjYzZTlhMzgxMTBjNDJkMjk3ZDNhOGQ2OGY4MGI1NDU0YTIxNTUyZjE0MDAwMDAwZThmYjFmY2YyMzYyM2U4NjRmMDliMzA1ZmI4ZTM1ZWRkMjBmNzU2NCIsIkRQQVBJSWRlbnRpdHkiOiJMTklQQzIwMzQ3NExcXEJvZGV0dEMifQ==
 
    This command will encrypt the provided string with DPAPI encryption and return the encoded cipher text.
    .EXAMPLE
    PS C:\> Protect-String "Secret message" -Encryption AES
    Enter Master Password: ********
    eyJFbmNyeXB0aW9uIjoiQUVTIiwiQ2lwaGVyVGV4dCI6IktUU2RYVG9tREt0M1N5eFN0OGsveGtxc2xjTjhseUZMQTllMDlWQWdkVTA9IiwiRFBBUElJZGVudGl0eSI6IiJ9
 
    This command will encrypt the provided string with AES 256-bit encryption. If no Master Password is found in the current session (set with Set-MasterPassword) then it will prompt for one to be set.
    .NOTES
    Version: 1.0
    Author: C. Bodett
    Creation Date: 3/28/2022
    Purpose/Change: Initial function development
    Version: 1.1
    Author: C. Bodett
    Creation Date: 5/12/2022
    Purpose/Change: changed to Generic List from ArrayList
    #>

    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [String]$InputString,
        [Parameter(Mandatory = $false, Position = 1)]
        [ValidateSet("DPAPI","AES")]
        [String]$Encryption = "DPAPI"
    )
    
    Begin {
        Write-Verbose "Encryption Type: $Encryption"
        If ($Encryption -eq "AES") {
            Write-Verbose "Retrieving Master Password key"
            $SecureAESKey = Get-AESMPVariable
            $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey
            #$AESKey = ConvertTo-Bytes -InputString $ClearTextAESKey -Encoding Unicode
            $AESKey = Convert-HexStringToByteArray -HexString $ClearTextAESKey
        }
        $OutputString = [System.Collections.Generic.List[String]]::New()
    }

    Process {
        Switch ($Encryption) {
            "DPAPI" {
                Try {
                    Write-Verbose "Converting string text to a SecureString object"
                    $ConvertedString = ConvertTo-SecureString $InputString -AsPlainText -Force | ConvertFrom-SecureString
                    $CipherObject = New-CipherObject -Encryption "DPAPI" -CipherText $ConvertedString
                    $CipherObject.DPAPIIdentity = Get-DPAPIIdentity
                    Write-Debug "DPAPI Identity: $($CipherObject.DPAPIIdentity)"
                    $JSONObject = ConvertTo-Json -InputObject $CipherObject -Compress
                    $JSONBytes = ConvertTo-Bytes -InputString $JSONObject -Encoding UTF8
                    $EncodedOutput = [System.Convert]::ToBase64String($JSONBytes)
                    $OutputString.add($EncodedOutput)
                } Catch {
                    Write-Error $_
                }
            }
            "AES" {
                Try {
                    Write-Verbose "Encrypting string text with AES 256-bit"
                    $ConvertedString = ConvertTo-AESCipherText -InputString $InputString -Key $AESKey -ErrorAction Stop
                    $CipherObject = New-CipherObject -Encryption "AES" -CipherText $ConvertedString
                    $JSONObject = ConvertTo-Json -InputObject $CipherObject -Compress
                    $JSONBytes = ConvertTo-Bytes -InputString $JSONObject -Encoding UTF8
                    $EncodedOutput = [System.Convert]::ToBase64String($JSONBytes)
                    $OutputString.add($EncodedOutput)
                } Catch {
                    Write-Error $_
                }
            }
        }
    }

    End {
        Write-Verbose "Protection complete. Returning $($OutputString.count) objects"
        Return $OutputString
    }
}
#Region - Remove-MasterPassword.ps1
Function Remove-MasterPassword {
    <#
    .Synopsis
    Removes the Master Password stored in the current session
    .Description
    The Master Password is stored as a Secure String object in memory for the current session. Should you wish to clear it manually you can do so with this function.
    .EXAMPLE
    PS C:\> Remove-MasterPassword
 
    This will erase the currently saved master password.
    .NOTES
    Version: 1.0
    Author: C. Bodett
    Creation Date: 3/28/2022
    Purpose/Change: Initial function development
    #>

    [cmdletbinding()]
    Param (
    )
    Write-Verbose "Removing master password from current session"
    Clear-AESMPVariable

}
#Region - Set-AESKeyConfig.ps1
Function Set-AESKeyConfig {
    <#
    .Synopsis
    Function to write settings for use with PBKDF2 to create an AES Key
    .Description
    Allows custom configuration of the parameters associated with the PBKDF2 generation. Namely the Salt, number of Iterations, and Hash type.
    .Parameter Salt
    Provide a custom string to be used as the Salt bytes in PBKDF2 generation. Must be at least 8 bytes in length. Alternatively you can also provide a base64 encoded string.
    .Parameter SaltBytes
    A byte array of at least 8 bytes can be provided for a custom salt value.
    .Parameter Iterations
    Specify the number of iterations PBKDF2 should use. 1000 is the default.
    .Parameter Hash
    Specify the Hash type used with PBKDF2. Accetable values are: 'MD5','SHA1','SHA256','SHA384','SHA512'.
    .Parameter Defaults
    Switch parameter that resets the AES Key Config file to default values.
    .NOTES
    Version: 2.0
    Author: C. Bodett
    Creation Date: 11/03/2022
    Purpose/Change: Changed Salt storage method to Base64 encoding for more reliable operation
    #>

    [cmdletbinding(DefaultParameterSetName = 'none')]
    Param (
        [Parameter(Mandatory = $false, ParameterSetName = "SaltString")]
        [ValidateScript({
            if ([System.Text.Encoding]::UTF8.GetBytes($_).Count -lt 8) {
                Throw "Salt must be at least 8 bytes in length"
            } else {
                return $true
            }
        })]
        [String]$Salt,
        [Parameter(Mandatory = $false, ParameterSetName = "SaltBytes")]
        [Byte[]]$SaltBytes,
        [Parameter(Mandatory = $false)]
        [Int32]$Iterations,
        [Parameter(Mandatory = $false)]
        [ValidateSet('MD5','SHA1','SHA256','SHA384','SHA512')]
        [String]$Hash,
        [Switch]$Defaults
    )

    Process {
        $ConfigFileName = "ProtectStringsConfig.psd1"
        $ConfigFilePath = Join-Path -Path $Env:LOCALAPPDATA  -ChildPath $ConfigFileName
        Write-Verbose "Config file path: $($ConfigFilePath)"
        if (-not (Test-Path  $ConfigFilePath) -or $Defaults) {
            Write-verbose "Defaults parameter provided or no config file present. Creating defaults"
            $DefaultConfigData = @"
@{
    Salt = 'fMK9w4HDtMO4d8Oa4pmAw6U+fknCqWvil4Q9w73DscOtw64='
    Iterations = 310000
    Hash = 'SHA256'
}
"@

            Try {
                $DefaultConfigData | Out-File -FilePath $ConfigFilePath -ErrorAction Stop
            } Catch {
                Throw $_
            }
        }

        Switch ($PSBoundParameters.Keys) {
            'Salt' {
                try { 
                    $Null = [System.Convert]::FromBase64String($Salt)
                } catch {
                    # suppress errors
                }
                if (-not ($?)) {
                    try {
                        $Salt = ConvertTo-Base64 -TextString $Salt
                    } catch {
                        Throw $_
                    }
                }
            }
            'SaltBytes' {
                if ($SaltBytes.Count -lt 8) {
                    Throw "Salt must be at least 8 bytes. Provided byte array is only $($SaltBytes.Count) bytes"
                }
                $Salt = ConvertTo-Base64 -Bytes $SaltBytes
            }
        }

        if ($($PSVersionTable.PSVersion.Major) -lt 5) {
            $Settings = Import-LocalizedData -BaseDirectory $ENV:LOCALAPPDATA -FileName $ConfigFileName
        } else {
            $Settings = Import-PowerShellDataFile -Path $ConfigFilePath
        }

        Switch ($PSBoundParameters.Keys) {
            'Salt' {$Settings.Salt = $Salt}
            'Iterations' {$Settings.Iterations = $Iterations}
            'Hash' {$Settings.Hash = $Hash}
        }

        $VMsg = @"
`r`n Saving settings...
        Salt........: $($Settings.Salt)
        Iterations..: $($Settings.Iterations)
        Hash........: $($Settings.Hash)
"@

        Write-Verbose $VMsg

        $OutString = "@{{`n{0}`n}}" -f ($(
                        ForEach ($Key in @($Settings.Keys)) {
                            If ($Settings[$Key] -is [Int32]) {
                                " $Key = " + ($Settings[$Key])
                            } Else {
                                    " $Key = " + "'{0}'" -f ($Settings[$Key])
                                }
                        }) -split "`n" -join "`n")
        $OutString | Out-File -FilePath $ConfigFilePath -ErrorAction Stop
    }
}
#Region - Set-MasterPassword.ps1
Function Set-MasterPassword {
    <#
    .Synopsis
    Securely retrieves from console the desired master password and saves it for the current session.
    .Description
    Takes a user provided master password as a secure string object and creates a unique AES 256 bit key from it and stores that as a SecureString object in memory for the current session.
    .Parameter MasterPassword
    If you already have a password in a variable as a SecureString object you can pass it to this function.
    .EXAMPLE
    PS C:\> Set-MasterPassword
    Enter Master Password: ********
 
    In this example you will be prompted to provide a password. It will then be silently stored in the current session.
    .EXAMPLE
    PS C:\> $Pass = Read-Host -AsSecureString
    *****************
    PS C:\> Set-MasterPassword -MasterPassword $Pass
 
 
    Here the desired master password is saved beforehand in the variable $Pass and then passed to the Set-MasterPassword function.
    .NOTES
    Version: 1.0
    Author: C. Bodett
    Creation Date: 3/28/2022
    Purpose/Change: Initial function development
    #>

    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $false, Position = 0)]
        [SecureString]$MasterPassword 
    )

    If (-not ($MasterPassword)) {
        $MasterPassword = Read-Host -Prompt "Enter Master Password" -AsSecureString
    }

    Try {
        Write-Verbose "Generating a 256-bit AES key from provided password"
        $SecureAESKey = ConvertTo-AESKey $MasterPassword
    } Catch {
        throw $_
    }
    Write-Verbose "Storing key for use within this session. Can be removed with Remove-MasterPassword"
    Set-AESMPVariable -MPKey $SecureAESKey
}
#Region - Unprotect-String.ps1
Function UnProtect-String {
    <#
    .Synopsis
    Decrypt a provided string using either DPAPI or AES encryption
    .Description
    This function will decode the provided protected text, and automatically determine if it was encrypted using DPAPI or AES encryption.
    If no master password has been set it will prompt for one.
    If there is a decryption problem it will notify.
    .Parameter InputString
    This is the protected text previously produced by the ProtectStrings module. Encryption type will be automatically determined.
    .EXAMPLE
    PS C:\> Protect-String "Secret message"
    eyJFbmNyeXB0aW9uIjoiRFBBUEkiLCJDaXBoZXJUZXh0IjoiMDEwMDAwMDBkMDhjOWRkZjAxMTVkMTExOGM3YTAwYzA0ZmMyOTdlYjAxMDAwMDAwODRkMTVhY2QwZjk5ZDM0NDllNzE5MTkwZGI0YzY2ZWUwMDAwMDAwMDAyMDAwMDAwMDAwMDAzNjYwMDAwYzAwMDAwMDAxMDAwMDAwMGMyNjFhZTY5YThjZjdlMTI0ZTJmZWI3MmVmMTk3YmRlMDAwMDAwMDAwNDgwMDAwMGEwMDAwMDAwMTAwMDAwMDA4NjUxZWJjZWY4MTE4MzEzMzljNDMyNjA5OWUxZWY3ZDIwMDAwMDAwZGQ3MDUyNGFkZGZlMmM5YzQyMDlhZDc2NjYzZTlhMzgxMTBjNDJkMjk3ZDNhOGQ2OGY4MGI1NDU0YTIxNTUyZjE0MDAwMDAwZThmYjFmY2YyMzYyM2U4NjRmMDliMzA1ZmI4ZTM1ZWRkMjBmNzU2NCIsIkRQQVBJSWRlbnRpdHkiOiJMTklQQzIwMzQ3NExcXEJvZGV0dEMifQ==
 
    This command will encrypt the provided string with DPAPI encryption and return the encoded cipher text.
 
    PS C:\> Unprotect-String 'eyJFbmNyeXB0aW9uIjoiRFBBUEkiLCJDaXBoZXJUZXh0IjoiMDEwMDAwMDBkMDhjOWRkZjAxMTVkMTExOGM3YTAwYzA0ZmMyOTdlYjAxMDAwMDAwODRkMTVhY2QwZjk5ZDM0NDllNzE5MTkwZGI0YzY2ZWUwMDAwMDAwMDAyMDAwMDAwMDAwMDAzNjYwMDAwYzAwMDAwMDAxMDAwMDAwMGMyNjFhZTY5YThjZjdlMTI0ZTJmZWI3MmVmMTk3YmRlMDAwMDAwMDAwNDgwMDAwMGEwMDAwMDAwMTAwMDAwMDA4NjUxZWJjZWY4MTE4MzEzMzljNDMyNjA5OWUxZWY3ZDIwMDAwMDAwZGQ3MDUyNGFkZGZlMmM5YzQyMDlhZDc2NjYzZTlhMzgxMTBjNDJkMjk3ZDNhOGQ2OGY4MGI1NDU0YTIxNTUyZjE0MDAwMDAwZThmYjFmY2YyMzYyM2U4NjRmMDliMzA1ZmI4ZTM1ZWRkMjBmNzU2NCIsIkRQQVBJSWRlbnRpdHkiOiJMTklQQzIwMzQ3NExcXEJvZGV0dEMifQ=='
    Secret message
 
    Feeding the previously output protected text to Unprotect-String will decrypt it and return the original string text.
    .EXAMPLE
    PS C:\> Protect-String "Secret message" -Encryption AES
    Enter Master Password: ********
    eyJFbmNyeXB0aW9uIjoiQUVTIiwiQ2lwaGVyVGV4dCI6IktUU2RYVG9tREt0M1N5eFN0OGsveGtxc2xjTjhseUZMQTllMDlWQWdkVTA9IiwiRFBBUElJZGVudGl0eSI6IiJ9
 
    This command will encrypt the provided string with AES 256-bit encryption. If no Master Password is found in the current session (set with Set-MasterPassword) then it will prompt for one to be set.
 
    PS C:\> Clear-MasterPassword
    PS C:\> Unprotect-String 'eyJFbmNyeXB0aW9uIjoiQUVTIiwiQ2lwaGVyVGV4dCI6IktUU2RYVG9tREt0M1N5eFN0OGsveGtxc2xjTjhseUZMQTllMDlWQWdkVTA9IiwiRFBBUElJZGVudGl0eSI6IiJ9'
    Enter Master Password: ********
    Secret message
 
    Clearing the master password from the sessino, providing the previously protected text to Unprotect-String will prompt for a master password and then decrypt the text and return the original string text.
    .NOTES
    Version: 1.0
    Author: C. Bodett
    Creation Date: 3/28/2022
    Purpose/Change: Initial function development
    Version: 1.1
    Author: C. Bodett
    Creation Date: 5/12/2022
    Purpose/Change: Fixed processing to handle pipeline input. Changed from Arraylist to Generic list
    Version: 1.2
    Author: C. Bodett
    Creation Date: 6/7/2022
    Purpose/Change: Redid Process block to accomodate new ConvertTo-CipherBlock function for better error handling on input text
    #>

    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [String]$InputString
    )
    
    Begin {
        $OutputString = [System.Collections.Generic.List[String]]::New()
    }

    Process {
        Write-Verbose "Converting supplied text to a Cipher Object for ProtectStrings"
        $CipherObject = Try {
            ConvertTo-CipherObject $InputString -ErrorAction Stop
        } Catch {
            Write-Debug $_
            Write-Warning "Supplied text could not be converted to a Cipher Object. Verify that it was produced by Protect-String."
            return
        }
        Write-Verbose "Encryption type: $($CipherObject.Encryption)"
        If ($CipherObject.Encryption -eq "AES") {
            $SecureAESKey = Get-AESMPVariable
            $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey
            #$AESKey = ConvertTo-Bytes -InputString $ClearTextAESKey -Encoding Unicode
            $AESKey = Convert-HexStringToByteArray -HexString $ClearTextAESKey
        }
        Switch ($CipherObject.Encryption) {
            "DPAPI" {
                Try {
                    Write-Verbose "Attempting to create a SecureString object from DPAPI cipher text"
                    $SecureStringObj = ConvertTo-SecureString -String $CipherObject.CipherText -ErrorAction Stop
                    $ConvertedString = ConvertFrom-SecureStringToPlainText -StringObj $SecureStringObj -ErrorAction Stop
                    $CorrectPassword = $true
                    $OutputString.add($ConvertedString)
                } Catch {
                    Write-Warning "Unable to decrypt as this user on this machine"
                    Write-Verbose "String protected by Identity: $($CipherObject.DPAPIIdentity)"
                    $CorrectPassword = $false
                }
            }
            "AES" {
                Try {
                    Write-Verbose "Attempting to decrypt AES cipher text"
                    $ConvertedString = ConvertFrom-AESCipherText -InputCipherText $CipherObject.CipherText -Key $AESKey -ErrorAction Stop
                    $CorrectPassword = $true
                    $OutputString.add($ConvertedString)
                } Catch {
                    Write-Warning "Incorrect AES Key. Please try again"
                    $CorrectPassword = $false
                    Clear-AESMPVariable
                }
            }
        }

    }

    End {
        If ($CorrectPassword) {
            Write-Verbose "Unprotect complete. Returning $($OutputString.count) objects"
            Return $OutputString
        }
    }
}
### --- PRIVATE FUNCTIONS --- ###
#Region - Clear-AESMPVariable.ps1
<#
.Synopsis
Clear the global variable of the previously stored master password/key
.NOTES
Version: 1.0
Author: C. Bodett
Creation Date: 03/28/2022
Purpose/Change: Initial function development
#>

Function Clear-AESMPVariable {
    [cmdletbinding()]
    Param (
    )

    Process {
        Write-Verbose "Clearing global variable where AES key is stored"
        Remove-Variable -Name "AESMP" -Force -Scope Global -ErrorAction SilentlyContinue
    }
}
#Region - Convert-HexStringToByteArray.ps1
<#.Synopsis
Converts a hexidecimal string in to an array of bytes
.Example
Any of the following is valid input
 
0x41,0x42,0x43,0x44
\x41\x42\x43\x44
41-42-43-44
41424344
#>

Function Convert-HexStringToByteArray {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true,ValueFromPipeline = $true,Position = 0)]
        [String]$HexString
    )

    Process {
        $Regex1 = '\b0x\B|\\\x78|-|,|:'
        # convert to lowercase and remove all possible deliminating characters
        $String = $HexString.ToLower() -replace $Regex1,''

        # Remove beginning and ending colons, and other detritus.
        $Regex2 = '^:+|:+$|x|\\'
        $String = $String -replace $Regex2,''

        $ByteArray = if ($String.Length -eq 1) {
                        [System.Convert]::ToByte($String,16)
                    } else {
                        $String -Split '(..)' -ne '' | foreach-object {
                            [System.Convert]::ToByte($_,16)
                        }
                    }
        Write-Output $ByteArray -NoEnumerate
    }

}
#Region - ConvertFrom-AESCipherText.ps1
<#
.Synopsis
Convert input AES Cipher text to plain text
#>

Function ConvertFrom-AESCipherText {
        [cmdletbinding()]
        param(
            [Parameter(ValueFromPipeline = $true,Position = 0,Mandatory = $true)]
            [string]$InputCipherText,
            [Parameter(Position = 1,Mandatory = $true)]
            [Byte[]]$Key
        )
    
        Process {
            Write-Verbose "Creating new AES Cipher object with supplied key"
            $AESCipher = Initialize-AESCipher -Key $Key
            Write-Verbose "Convert input text from Base64"
            $EncryptedBytes = [System.Convert]::FromBase64String($InputCipherText)
            Write-Verbose "Using the first 16 bytes as the initialization vector"
            $AESCipher.IV = $EncryptedBytes[0..15]
            Write-Verbose "Decrypting AES cipher text"
            $Decryptor = $AESCipher.CreateDecryptor()
            $UnencryptedBytes = $Decryptor.TransformFinalBlock($EncryptedBytes, 16, $EncryptedBytes.Length - 16)
            Write-Verbose "Converting from bytes to string text using UTF8 encoding"
            $ConvertedString = ConvertFrom-Bytes -InputBytes $UnencryptedBytes -Encoding UTF8
        }
        End {
            Write-Verbose "Disposing of AES Cipher object"
            $AESCipher.Dispose()
            return $ConvertedString
        }

}
#Region - ConvertFrom-Base64.ps1
<#
.Synopsis
Converts a Base64 string in to plaintext.
.Description
Takes a Base64 string as a parameter, either directly or from the pipeline, and converts it in to plaintext.
.Parameter TextString
The Base64 string. Can come from the pipeline.
.Parameter Encoding
Default encoding is UTF8, but this can be Unicode or UTF8 if you're having problems.
.Parameter OutputType
Select whether to return the decoded value as a string or a byte array
.NOTES
Version: 1.0
Author: C. Bodett
Creation Date: 9/14/2021
Purpose/Change: Initial function development.
#>

Function ConvertFrom-Base64 {
    [cmdletbinding()]
    Param (
        [Parameter(ValueFromPipeline = $true, Position = 0, Mandatory = $true)]
        [String]$TextString,
        [Parameter(Position = 1)]
        [ValidateSet('UTF8','Unicode')]
        [String]$Encoding = 'UTF8',
        [Parameter(Position = 2)]
        [ValidateSet('Bytes','String')]
        [String]$OutputType = 'String'
    )

    if ($OutputType -eq 'String') {
        $Decoded = [System.Text.Encoding]::$encoding.GetString([System.Convert]::FromBase64String($TextString))
    } else {
        $Decoded = [System.Convert]::FromBase64String($TextString)
    }
    return $Decoded
}
#Region - ConvertFrom-Bytes.ps1
<#
.Synopsis
Gets string from supplied input bytes
#>

Function ConvertFrom-Bytes{
        [cmdletbinding()]
        param(
        [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)]
        [Byte[]]$InputBytes,
        [Parameter(Position=1)]
        [ValidateSet('UTF8','Unicode')]
        [string]$Encoding = 'Unicode'
        )
    
        Write-Verbose "Converting from bytes to string using $Encoding encoding"
        $OutputString = [System.Text.Encoding]::$Encoding.GetString($InputBytes)
        return $OutputString
    }
    
#Region - ConvertFrom-SecureStringToPlainText.ps1
Function ConvertFrom-SecureStringToPlainText {
    [cmdletbinding()]
    param(
        [parameter(Position=0,HelpMessage="Must provide a SecureString object",
        ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [ValidateNotNull()]
        [System.Security.SecureString]$StringObj
        )
    Process {
        $BSTR = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($StringObj)
        $PlainText = [Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
        [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
    }
    End {
        $PlainText
    }
} 
#Region - ConvertTo-AESCipherText.ps1
<#
.Synopsis
Convert input string to AES encrypted cipher text
#>

Function ConvertTo-AESCipherText {
    [cmdletbinding()]
    param(
        [Parameter(ValueFromPipeline = $true,Position = 0,Mandatory = $true)]
        [string]$InputString,
        [Parameter(Position = 1,Mandatory = $true)]
        [Byte[]]$Key
    )

    Process {
            $InitializationVector = [System.Byte[]]::new(16)
            Get-RandomBytes -Bytes $InitializationVector
            $AESCipher = Initialize-AESCipher -Key $Key
            $AESCipher.IV = $InitializationVector
            $ClearTextBytes = ConvertTo-Bytes -InputString $InputString -Encoding UTF8
            $Encryptor =  $AESCipher.CreateEncryptor()
            $EncryptedBytes = $Encryptor.TransformFinalBlock($ClearTextBytes, 0, $ClearTextBytes.Length)
            [byte[]]$FullData = $AESCipher.IV + $EncryptedBytes
            $ConvertedString = [System.Convert]::ToBase64String($FullData)
            $DebugInfo = @"
`r`n Input String Length : $($InputString.Length)
  Initialization Vector : $($InitializationVector.Count) Bytes
  Text Encoding : UTF8
  Output Encoding : Base64
"@

            Write-Debug $DebugInfo
        }

    End {
        $AESCipher.Dispose()
        return $ConvertedString
        }

}
#Region - ConvertTo-AESKey.ps1
<#
.Synopsis
Function to convert a SecureString object to a unique 32 Byte array for use with AES 256bit encryption
.NOTES
Version: 3.0
Author: C. Bodett
Creation Date: 11/03/2022
Purpose/Change: Changed salt storage method to Base64 encoding for more reliable operation.
#>

Function ConvertTo-AESKey {
    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [System.Security.SecureString]$SecureStringInput,
        [Parameter(Mandatory = $false)]
        [Switch]$ByteArray
    )

    Process {
        Write-Verbose "Retrieving AESKey settings"
        $Settings = Get-AESKeyConfig 
        Write-Verbose "Converting Salt to byte array"
        $SaltBytes = ConvertFrom-Base64 -Textstring $($Settings.Salt) -OutputType Bytes
        # Temporarily plaintext our SecureString password input. There's really no way around this.
        Write-Verbose "Converting supplied SecureString text to plaintext"
        $Password = ConvertFrom-SecureStringToPlainText $SecureStringInput
        # Create our PBKDF2 object and instantiate it with the necessary values
        $VMsg = @"
`r`n Creating PBKDF2 Object
        Password....: $("*"*$($Password.Length))
        Salt........: $($Settings.Salt)
        Iterations..: $($Settings.Iterations)
        Hash........: $($Settings.Hash)
"@

        Write-Verbose $VMsg
        $PBKDF2 = New-Object Security.Cryptography.Rfc2898DeriveBytes  -ArgumentList @($Password, $SaltBytes, $($Settings.Iterations), $($Settings.Hash))
        # Generate our AES Key
        Write-Verbose "Generating 32 byte key"
        $Key = $PBKDF2.GetBytes(32)
        # If the ByteArray switch is provided, return a plaintext byte array, otherwise turn our AES key in to a SecureString object
        If ($ByteArray) {
            Write-Verbose "ByteArray switch provided. Returning clear text array of bytes"
            $KeyOutput = $Key
        } Else {
            $KeyAsSecureString = ConvertTo-SecureString -String $([System.BitConverter]::ToString($Key)) -AsPlainText -Force
            $KeyOutput = $KeyAsSecureString
        }
        return $KeyOutput
    }
}
#Region - ConvertTo-Base64.ps1
<#
.Synopsis
Converts a plaintext string in to Base64.
.Description
Takes a plaintext string as a parameter, either directly or from the pipeline, and converts it in to Base64.
.Parameter TextString
The plaintext string. Can come from the pipeline.
.Parameter Encoding
Default encoding is UTF8, but this can be Unicode or UTF8 if you're having problems.
.NOTES
Version: 1.0
Author: C. Bodett
Creation Date: 9/14/2021
Purpose/Change: Initial function development.
#>

Function ConvertTo-Base64{
    [cmdletbinding()]
    Param (
        [Parameter(ValueFromPipeline = $true, Position = 0, Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [String]$TextString,
        [Parameter(ValueFromPipeline = $false, Position = 0, Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [Byte[]]$Bytes,
        [Parameter(Position = 1)]
        [ValidateSet('UTF8','Unicode')]
        [String]$Encoding = 'UTF8'
    )

    Switch ($PSBoundParameters.Keys) {
        'TextString' {
            $Encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::$Encoding.GetBytes($TextString))
        }
        'Bytes' {
            $Encoded = [System.Convert]::ToBase64String($Bytes)
        }
    }
    return $Encoded
}
#Region - ConvertTo-Bytes.ps1
<#
.Synopsis
Gets bytes from supplied input string
#>

Function ConvertTo-Bytes{
    [cmdletbinding()]
    param(
    [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)]
    [string]$InputString,
    [Parameter(Position=1)]
    [ValidateSet('UTF8','Unicode')]
    [string]$Encoding = 'Unicode'
    )

    Write-Debug "Converting Input text to bytes with $Encoding encoding"
    Write-Debug "Input Text: $InputString"
    $Bytes = [System.Text.Encoding]::$Encoding.GetBytes($InputString)
    return $Bytes
}
#Region - ConvertTo-CipherObject.ps1
<#
.Synopsis
Convert output from Protect-String in to a Cipher Object
#>

Function ConvertTo-CipherObject {
    [cmdletbinding()]
    Param (
        [String]$B64String
    )

    $JSONBytes = Try {
        [System.Convert]::FromBase64String($B64String)
    } Catch {
        Write-Verbose "Unable to decode Input String. Expecting Base64"
        throw
    }

    $JSON = Try {
        ConvertFrom-Bytes -InputBytes $JSONBytes -Encoding UTF8
    } Catch {
        Write-Verbose "Unable to convert bytes with UTF8 encoding"
        throw
    }

    $ObjectData = Try {
        ConvertFrom-Json -InputObject $JSON -ErrorAction Stop
    } Catch {
        Write-Verbose "Unable to convert data from JSON"
        throw
    }
    $CipherObject = Try {
        New-CipherObject -Encryption $($ObjectData.Encryption) -CipherText $($ObjectData.CipherText)
    } Catch {
        Write-Verbose "Unable to create Cipher Object"
        throw
    }
    $CipherObject.DPAPIIdentity = $ObjectData.DPAPIIdentity
    return $CipherObject
}
#Region - Get-AESKeyConfig.ps1
<#
.Synopsis
Function to retrieve settings for use with PBKDF2 to create an AES Key
.NOTES
Version: 2.0
Author: C. Bodett
Creation Date: 11/03/2022
Purpose/Change: Changed Salt storage method to Base64 encoding for more reliable operation
#>

Function Get-AESKeyConfig {
    [cmdletbinding()]
    Param (
        # No Parameters
    )

    Process {
        $ConfigFileName = "ProtectStringsConfig.psd1"
        $ConfigFilePath = Join-Path -Path $Env:LOCALAPPDATA  -ChildPath $ConfigFileName

        if (-not (Test-Path  $ConfigFilePath)) {
            $DefaultConfigData = @"
@{
    Salt = 'fMK9w4HDtMO4d8Oa4pmAw6U+fknCqWvil4Q9w73DscOtw64='
    Iterations = 310000
    Hash = 'SHA256'
}
"@

            Try {
                $DefaultConfigData | Out-File -FilePath $ConfigFilePath -ErrorAction Stop
            } Catch {
                Write-Verbose "Failed to create configuration file for PBKDF2 settings. Temporarily loading defaults for this session."
                $Settings = Invoke-Expression $DefaultConfigData
                return $Settings
            }
        }

        if ($($PSVersionTable.PSVersion.Major) -lt 5) {
            $Settings = Import-LocalizedData -BaseDirectory $ENV:LOCALAPPDATA -FileName $ConfigFileName
        } else {
            $Settings = Import-PowerShellDataFile -Path $ConfigFilePath
        }

        return $Settings
    }
}
#Region - Get-AESMPVariable.ps1
<#
.Synopsis
Get the password derived key to a global session variable for future use.
.NOTES
Version: 1.0
Author: C. Bodett
Creation Date: 03/27/2022
Purpose/Change: Initial function development
Version: 1.1
Author: C. Bodett
Creation Date: 05/12/2022
Purpose/Change: changed logic from if/ifelse to switch statement
#>

Function Get-AESMPVariable {
    [cmdletbinding()]
    Param (
        [Switch]$Boolean
    )

    Process {
        $SecureAESKey = Try {
            $Global:AESMP
        } Catch {
            # do nothing
        }

        <#
        If (-not ($SecureAESKey) -and -not ($Boolean)) {
            Set-MasterPassword
            $SecureAESKey = Get-AESMPVariable
        } ElseIf (-not ($SecureAESKey) -and $Boolean) {
            Write-Verbose "No Master Password key found"
            return $false
        }
        #>

        Switch ('{0}{1}' -f [int][bool]$SecureAESKey,[int][bool]$Boolean) {
            "10" {
                Write-Debug "Master Password key found"
            }
            "11" {
                Write-Debug "Master Password key found"
                return $true
            }
            "01" {
                Write-Debug "No Master Password key found"
                return $false
            }
            "00" {
                Write-Debug "No Master Password key found"
                Set-MasterPassword
                $SecureAESKey = Get-AESMPVariable
            }
        }
        
        return $SecureAESKey

    }
}
#Region - Get-DPAPIIdentity.ps1
<#
.Synopsis
Get the current username and computer name
#>

Function Get-DPAPIIdentity {
    [cmdletbinding()]
    Param (
    )
    
    Write-Debug "Current ENV:Computername : $ENV:COMPUTERNAME"
    Write-Debug "Current ENV:Computername : $ENV:USERNAME"
    Write-Debug "Creating DPAPI Identity information"
    $Output = '{0}\{1}' -f $ENV:COMPUTERNAME,$ENV:USERNAME
    return $Output
}
#Region - Get-RandomBytes.ps1
<#
.Synopsis
A Function to leverage the .NET Random Number Generator
#>

Function Get-RandomBytes {
    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [Byte[]]$Bytes
    )

    $RNG = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
    $RNG.GetBytes($Bytes)

}
#Region - Initialize-AESCipher.ps1
<#
.Synopsis
A Function to initiate the .NET AESCryptoServiceProvider
#>

Function Initialize-AESCipher {
    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [Byte[]]$Key
    )

    $AESServiceProvider = New-Object System.Security.Cryptography.AesCryptoServiceProvider
    $AESServiceProvider.Key = $Key
    return $AESServiceProvider

}
#Region - New-CipherObject.ps1
<#
.Synopsis
Create a new CipherObject
#>

Function New-CipherObject {
    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateSet("DPAPI","AES")]
        [String]$Encryption,
        [Parameter(Mandatory = $true, Position = 1)]
        [String]$CipherText
    )
 
    [CipherObject]::New($Encryption,$CipherText)
    
}
#Region - Set-AESMPVariable.ps1
<#
.Synopsis
Set the password derived key to a global session variable for future use.
.NOTES
Version: 1.0
Author: C. Bodett
Creation Date: 03/27/2022
Purpose/Change: Initial function development
#>

Function Set-AESMPVariable {
    [cmdletbinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [SecureString]$MPKey
    )

    Process {
        Write-Verbose "Creating new variable globally to store AES Key"
        New-Variable -Name "AESMP" -Value $MPKey -Option AllScope -Scope Global -Force
    }
}
### --- CLASS DEFINITIONS --- ###
#Region - CipherObject.ps1
Class CipherObject {
    [String]  $Encryption
    [String]  $CipherText
    hidden[String]  $DPAPIIdentity
    CipherObject ([String]$Encryption, [String]$CipherText) {
        $this.Encryption = $Encryption
        $this.CipherText = $CipherText
        $this.DPAPIIdentity = $null
    }
}