-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSVTokenizer.ps1
More file actions
286 lines (286 loc) · 12.9 KB
/
CSVTokenizer.ps1
File metadata and controls
286 lines (286 loc) · 12.9 KB
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
function HelpPage(){
cls
Write-Host "================================================================================"
Write-Host "| Help Menu |"
Write-Host "================================================================================"
Write-Host "| This script is designed to convert sensitive data in CSV columns |"
Write-Host "| into unique tokens and provide a keyfile for later de-tokenization. |"
Write-Host "================================================================================"
Write-Host "| Column Selection |"
Write-Host "================================================================================"
Write-Host "| - = Go to previous column header. |"
Write-Host "| + = Go to next column header. |"
Write-Host "| # = Go to specified column header (Index must be in range) |"
Write-Host "| ? = Search for column header by name. |"
Write-Host "| x = Toggle column header selection. |"
Write-Host "| S = Show column header selection summary. |"
Write-Host "| . = Continue with the tokenization operation with the current selections. |"
Write-Host "| QUIT = End script execution. |"
Write-Host "| H = Show this help menu. |"
Write-Host "================================================================================"
Write-Host "| Arguments Mode |"
Write-Host "================================================================================"
Write-Host "| Tokenize Mode: |"
Write-Host "| Usage: ./CSVTokenizer.ps1 -d ',' -c '`"Name`",`"Address`",`"Phone Number`"' |"
Write-Host "| |"
Write-Host "| `"-c`" = Designate columns to tokenize in CSV format. |"
Write-Host "| `"-d`" = Set delimiter to be used in processing CSV file. |"
Write-Host "================================================================================"
Write-Host "| De-tokenize Mode: |"
Write-Host "| Usage: ./CSVTokenizer.ps1 -t *TOKENIZED_FILEPATH* *TOKEN_KEYS_FILEPATH* |"
Write-Host "================================================================================"
Read-Host "ENTER TO CONTINUE..."
}
function Summary(){
param($SelectedHeaders)
cls
$TotalSelected = 0
Write-Host "================================================================================"
Write-Host "| Column Header Selection Summary |"
foreach ($HeaderTitle in $Headers){
Write-Host "================================================================================"
Write-Host "Column Title: "$HeaderTitle
Write-Host "Index: "$([array]::indexof($Headers,$HeaderTitle) + 1)
if ([array]::indexof($Headers, $HeaderTitle) -in $SelectedHeaders){
Write-Host "Included: True"
$TotalSelected++
}
else{
Write-Host "Included: False"
}
}
Write-Host "********************************************************************************"
Write-Host "Total Columns in Input File: "$Headers.Length
Write-Host "Total Columns Included: "$TotalSelected
Write-Host "********************************************************************************".
}
function SearchColumns(){
param($CSVCOlumnTitles)
$QueryItems = @()
$Query = Read-Host "Enter search query."
if ($Query -match '^[a-zA-Z0-9._@-]{1,100}$'){
foreach ($Title in $CSVCOlumnTitles){
if ($Title -match $Query){
$QueryItems += $Title
}
}
}
else{
Write-Host "Invalid input"
sleep 2
SearchColumns @($CSVCOlumnTitles)
}
if ($QueryItems.Length -lt 1){
Write-Host "No matches found for query `"$Query`"."
sleep 2
SearchColumns @($CSVCOlumnTitles)
}
elseif ($QueryItems.Length -eq 1){
$SelectedHeader = $CSVCOlumnTitles | where {$_ -eq $($QueryItems[0])}
return $([array]::indexof($CSVCOlumnTitles,$SelectedHeader))
}
else{
Write-Host "Multiple users found for query `"$Query`":"
foreach ($QueryResult in $QueryItems){
Write-Host $([array]::indexof($QueryItems,$QueryResult) + 1)". "$QueryResult
}
$SelectedEntry = Read-Host "Please select an entry. (1..$($QueryItems.Length))"
if ($SelectedEntry -in 1..$($QueryItems.Length)){
$SelectedHeader = $CSVCOlumnTitles | where {$_ -eq $($QueryItems[$($SelectedEntry - 1)])}
return $([array]::indexof($CSVCOlumnTitles,$SelectedHeader))
}
else{
Write-Host "ERROR: Selection `"$SelectedEntry`" out of range!"
sleep 2
SearchColumns @($CSVCOlumnTitles)
}
}
}
function TableSelection(){
param($CSVColumnHeaders, $HeaderSelection)
$ListMaxIndex = $($($CSVColumnHeaders.Length) - 1)
$Index=0
while ($Index -in 0..$ListMaxIndex){
cls
$CurrentIndex = [array]::indexof($CSVColumnHeaders,($Headers | where {$_ -eq ($CSVColumnHeaders[$Index])}))
Write-Host "================================================================================"
Write-Host "| Column Selection |"
Write-Host "================================================================================"
Write-Host " Current Column Title: "$($CSVColumnHeaders[$Index])
Write-Host " Current Index: $($CurrentIndex+1)"
if ($CurrentIndex -in $HeaderSelection){
Write-Host " Item Selected: True"
}
else{
Write-Host " Item Selected: False"
}
Write-Host " Total Items: "$CSVColumnHeaders.Length
Write-Host "================================================================================"
Write-Host "| - = Previous, + = Next, # = Go to, x = Toggle Select, H = Help, . = Done |"
Write-Host "================================================================================"
$Reply = Read-Host "> "
switch ($Reply) {
'+' {cls; $Index++; Break}
'-' {cls; $Index--; Break}
'x' {cls; if($CurrentIndex -in $HeaderSelection){$HeaderSelection = ($HeaderSelection | Where-Object {$_ -ne $CurrentIndex})}else{$HeaderSelection += $CurrentIndex}; Break}
'H' {HelpPage; Break}
'S' {Summary($HeaderSelection); cls; Read-Host "ENTER TO CONTINUE..."; Break}
'?' {$Index = (SearchColumns($CSVColumnHeaders)); Break}
'#' {$DesiredIndex = Read-Host "Please enter the index you want to jump to. (1..$($Headers.Length))"; if ($DesiredIndex -in 1..$($Headers.Length)){$Index = $($DesiredIndex - 1)}else{Write-Host "ERROR: Selection `"$DesiredIndex`" is out of range!"; sleep 2}}
'.' {cls; Summary($HeaderSelection); $ConfirmRun = Read-Host "Are you sure you want to initiate tokenization process for the currently selected columns? (y,n)"; if ($ConfirmRun -eq 'y' -or $ConfirmRun -eq 'Y'){return $HeaderSelection; exit}; Break}
'QUIT' {$ConfirmQuit = Read-Host "Are you sure you want to exit? (y,n)"; if($ConfirmQuit -eq 'y' -or $ConfirmQuit -eq 'Y'){cls; exit}; Break}
}
if ($Index -gt $ListMaxIndex){
$Index--
}
elseif ($Index -lt 0){
$Index++
}
}
}
function FileTokenizer(){
param($InputFilePath, $ColumnTitleData, $ColumnsToMask, $CSVDelimiter)
$OutputFilePath = (Split-Path -Path $InputFilePath -Parent)
$OutputCSVFileName = "Tokenized-$(Split-Path -Path $InputFilePath -Leaf)"
Add-Type -AssemblyName Microsoft.VisualBasic
$TokenKeyData = @{}
$CSVFileReader = New-Object Microsoft.VisualBasic.FileIO.TextFieldParser $InputFilePath
$CSVFileReader.TextFieldType = [Microsoft.VisualBasic.FileIO.FieldType]::Delimited
$CSVFileReader.SetDelimiters($CSVDelimiter)
$CSVFileReader.HasFieldsEnclosedInQuotes = $true
$CSVFileWriter = [System.IO.StreamWriter]::new("$OutputFilePath\$OutputCSVFileName")
$CSVFileWriter.WriteLine(($ColumnTitleData -join $CSVDelimiter))
$null = $CSVFileReader.ReadFields()
$TokenCounter = 0
while (-not $CSVFileReader.EndOfData) {
$RowValues = $CSVFileReader.ReadFields()
foreach ($Column in $ColumnsToMask) {
if ($Column -lt $RowValues.Length) {
$OriginalValue = $RowValues[$Column]
if(!($TokenKeyData.ContainsKey($OriginalValue))){
$TokenKeyData[$OriginalValue] = "T[{0:X}]" -f $TokenCounter
$TokenCounter++
}
$RowValues[$Column] = $TokenKeyData[$OriginalValue]
}
}
$CSVFileWriter.WriteLine(($RowValues -join $CSVDelimiter))
}
$CSVFileReader.Close()
$CSVFileWriter.Close()
$KeyFileData = @{}
foreach ($Key in $TokenKeyData.Keys){
$Base64TextValue = ([System.Convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes($Key))))
$KeyFileData["$Base64TextValue"] = $TokenKeyData[$Key]
}
$OutputPath = (Split-Path -Path $InputFile -Parent)
$OutputKeyFileName = "$($(Split-Path -Path $InputFile -Leaf).TrimEnd('.csv'))-TokenKeys.JSON"
$JSONKeyData = [PSCustomObject]$KeyFileData
$JSONKeyData | ConvertTo-Json | Set-Content "$OutputPath\$OutputKeyFileName"
$JSONKeyData = [PSCustomObject]$KeyFileData
}
function Detokenize(){
param($InputTokenizedFilePath, $InputKeyFilePath)
cls
Write-Host "De-tokenizing file: `"$InputTokenizedFilePath`" with keyfile: `"$InputKeyFilePath`"."
$OutputFilePath = (Split-Path -Path $InputTokenizedFilePath -Parent)
$OutputFileName = "DeTokenized-$(Split-Path -Path $InputTokenizedFilePath -Leaf)"
$TokenizedFileData = (Get-Content -Path $InputTokenizedFilePath)
$TokenMapData = (Get-Content -Path $InputKeyFilePath | ConvertFrom-JSON)
$TokenTranslations = (Get-Content -Path $InputKeyFilePath | ConvertFrom-JSON | Get-Member -MemberType NoteProperty | Select Name)
$OutputFileContent = Get-Content -Path $InputTokenizedFilePath
foreach ($B64Value in $TokenTranslations){
$CurrentToken = ($TokenMapData.($B64Value.Name))
$CurrentOriginalValue = ([System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("$($B64Value.Name)")))
$OutputFileContent = $OutputFileContent.Replace($CurrentToken,$CurrentOriginalValue)
}
Set-Content -Path "$OutputFilePath\$OutputFileName" -Value $OutputFileContent
cls
Write-Host "Successfully de-tokenized file `"$InputTokenizedFilePath`"."
}
cls
Add-Type -AssemblyName Microsoft.VisualBasic
if ($args[0]){
if ($args[0] -eq '-t'){
$InputTokenizedFile = [string]$args[1]
$InputKeyFile = [string]$args[2]
Detokenize $InputTokenizedFile $InputKeyFile
exit
}
else{
$InputFile = [string]$args[0]
if ([string]$args[1] -eq '-d'){
$Delimiter = [string]$args[2]
}
elseif ([string]$args[1] -eq '-c'){
$SelectedColumnNames = [string]$args[2]
}
if ([string]$args[3] -eq '-c'){
$SelectedColumnNames = [string]$args[4]
}
elseif ([string]$args[3] -eq '-d'){
$Delimiter = [string]$args[4]
}
$SelectedColumnList = $SelectedColumnNames -split $Delimiter
}
}
else{
$InputMode = Read-Host "Would you like to tokenize or de-tokenize? (t,d)"
if ($InputMode -eq "d" -or $ImputMode -eq "D"){
cls
$InputTokenizedFile = Read-Host "Please enter the full path of the file to de-tokenize"
while (!(Test-Path $InputTokenizedFile -PathType Leaf)){
if (!(Test-Path $InputTokenizedFile -PathType Leaf)){
cls
Write-Host "ERROR: $InputTokenizedFile - Path invalid."
$InputTokenizedFile = Read-Host "Please enter the full path of the file to de-tokenize"
}
}
cls
$InputKeyFile = Read-Host "Please enter the full path of the TokenKeys file"
while (!(Test-Path $InputKeyFile -PathType Leaf)){
if (!(Test-Path $InputKeyFile -PathType Leaf)){
cls
Write-Host "ERROR: $InputKeyFile - Path invalid."
$InputKeyFile = Read-Host "Please enter the full path of the TokenKeys file"
}
}
Detokenize $InputTokenizedFile $InputKeyFile
exit
}
else{
$InputFile = Read-Host "Please enter the full path of the CSV file to tokenize"
cls
$Delimiter = Read-Host "Set file delimiter (default ',')"
}
}
if (!($Delimiter)){
$Delimiter = ','
}
$FileReaderTitle = New-Object Microsoft.VisualBasic.FileIO.TextFieldParser $InputFile
$FileReaderTitle.TextFieldType = [Microsoft.VisualBasic.FileIO.FieldType]::Delimited
$FileReaderTitle.SetDelimiters($Delimiter)
$FileReaderTitle.HasFieldsEnclosedInQuotes = $true
$Headers = $FileReaderTitle.ReadFields()
$FileReaderTitle.Close()
if ($args[0]){
$SelectedColumns = @()
foreach ($SelectedName in $SelectedColumnList){
$SelectedColumns += ([array]::indexof($Headers,$SelectedName))
}
}
else{
$SelectedColumns = TableSelection $Headers @()
}
while (!(Test-Path $InputFile -PathType Leaf)){
if (!(Test-Path $InputFile -PathType Leaf)){
cls
Write-Host "ERROR: $InputFile - Path invalid."
$InputFile = Read-Host "Please enter the full path of the CSV file to tokenize"
}
}
cls
Write-Host "Tokenizing CSV File `"$InputFile`"..."
FileTokenizer $InputFile $Headers $SelectedColumns $Delimiter
cls
Write-Host "Successfully tokenized file `"$InputFile`"."