Created
October 20, 2020 03:00
-
-
Save Wind010/e73118b24a6c224e9b67d38d3c19a8a0 to your computer and use it in GitHub Desktop.
Attribute to and addapted from https://github.com/ghost1face/base62/blob/master/Base62/Base62Converter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Base62Encode([string] $inputStr = [Guid]::NewGuid().ToString()) | |
{ | |
[byte[]] $byteArr = [system.Text.Encoding]::UTF8.GetBytes($inputStr) | |
$converted = BaseConvert $byteArr 256 62 | |
$sb = [System.Text.StringBuilder]::new() | |
for ($i = 0; $i -lt $converted.Length; $i++) { | |
$sb.Append($CharacterSet[$converted[$i]]) | Out-Null | |
} | |
return $sb.ToString() | |
} | |
function Base62Decode([string] $inputStr) | |
{ | |
[byte[]] $byteArr = [System.Byte[]]::CreateInstance([System.Byte], $inputStr.Length) | |
for ($i = 0; $i -lt $byteArr.Length; $i++) { | |
$byteArr[$i] = $CharacterSet.IndexOf($inputStr[$i]) -as [byte] | |
} | |
$converted = BaseConvert $byteArr 62 256 | |
return [system.Text.Encoding]::UTF8.GetString($converted, 0, $converted.Length) | |
} | |
function BaseConvert([byte[]] $source, [int] $sourceBase, [int] $targetBase) | |
{ | |
$result = New-Object Collections.Generic.List[Int] | |
[int] $count = 0 | |
while (($count = $source.Length) -gt 0) { | |
$quotient = New-Object Collections.Generic.List[byte] | |
[int] $remainder = 0 | |
for ($i = 0; $i -lt $count; $i++) { | |
[int] $accumalator = $source[$i] + $remainder * $sourceBase | |
[byte] $digit = [System.Convert]::ToByte(($accumalator - ($accumalator % $targetBase)) / $targetBase) | |
$remainder = $accumalator % $targetBase | |
if ($quotient.Count -gt 0 -OR $digit -ne 0) { | |
$quotient.Add($digit) | |
} | |
} | |
$result.Insert(0, $remainder) | |
$source = $quotient.ToArray() | |
} | |
[byte[]] $output = [System.Byte[]]::CreateInstance([System.Byte], $result.Count) | |
for ($i = 0; $i -lt $result.Count; $i++) { | |
$output[$i] = $result[$i] -as [byte] | |
} | |
return $output | |
} | |
Export-ModuleMember -Function * -Alias * |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment