Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/base64-candidate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Base64String 1.3.0 candidate checks
on:
push:
branches: [prepare/base64string-1.3.0, base64String/release/latest]
pull_request:
branches: [base64String/release/latest]
permissions:
contents: read
jobs:
candidate:
# Pin the reusable workflow to a commit so candidate checks cannot change unexpectedly.
uses: stadub/PowershellScripts/.github/workflows/validate-release-candidate.yml@48556064087652ae6fc24d6255a117486b9b13f9
with:
module: Base64String
version: '1.3.0'
source_sha: ${{ github.event.pull_request.head.sha || github.sha }}
automation_sha: 48556064087652ae6fc24d6255a117486b9b13f9
143 changes: 103 additions & 40 deletions Shared-Functions/Base64String/Base64String.Tests.ps1
Original file line number Diff line number Diff line change
@@ -1,55 +1,118 @@

$NoExport = $true
$ModuleDevelopment = $true
$DebugPreference = "Continue"

Set-StrictMode -version Latest

$here = Split-Path -Parent $MyInvocation.MyCommand.Path

Import-Module .\Base64String.psd1

Describe "ConvertTo-Base64String" {

It "Encodes text to Base64" {
$text="text"
$encoded="dABlAHgAdAA="

$result = ConvertTo-Base64String -Value $text -UrlSafe $true

$result | Should -Be $encoded
Import-Module (Join-Path $here 'Base64String.psd1') -Force

Describe 'Base64String encoding compatibility' {
It 'preserves the default UTF-16 little-endian bytes' {
ConvertTo-Base64String 'text' | Should -BeExactly 'dABlAHgAdAA='
ConvertTo-Base64String -Text 'text' | Should -BeExactly 'dABlAHgAdAA='
ConvertFrom-Base64String 'dABlAHgAdAA=' | Should -BeExactly 'text'
ConvertFrom-Base64String 'MQAyADMAcQB3AGUA' | Should -BeExactly '123qwe'
}

It "UrlSafe produce urlsafe text " {
$text="text"
$encoded="dABlAHgAdAA"

$result = ConvertTo-Base64String -Value $text -UrlSafe $true


$result | Should -Be $encoded
It 'preserves Unicode and the historical 1-ending regression' {
# Code points keep this test readable by Windows PowerShell without a UTF-8 BOM.
$text = '.d_''+' + [char]0x2642 + [char]0xA2 + [char]0xA3 + '1'
$expected = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($text))
ConvertTo-Base64String $text | Should -BeExactly $expected
ConvertFrom-Base64String $expected | Should -BeExactly $text
ConvertFrom-Base64String $expected.TrimEnd('=') | Should -BeExactly $text
}
}

Describe "ConvertFrom-Base64String" {
It 'interoperates with the non-ASCII UTF-8 example from issue 22' {
$text = '.d_''+' + [char]0x2642 + [char]0xA2 + [char]0xA3
ConvertTo-Base64String $text -Encoding UTF8 | Should -BeExactly 'LmRfJyvimYLCosKj'
ConvertFrom-Base64String 'LmRfJyvimYLCosKj' -Encoding UTF8 | Should -BeExactly $text
}

It "Decodes text from Base64" {
$encoded="MQAyADMAcQB3AGUA"
$text="123qwe"
It 'accepts supported encoding <Encoding>' -TestCases @(
@{ Encoding = 'Unicode'; Expected = 'QQA=' }
@{ Encoding = 'UTF8'; Expected = 'QQ==' }
@{ Encoding = 'BigEndianUnicode'; Expected = 'AEE=' }
@{ Encoding = 'UTF32'; Expected = 'QQAAAA==' }
@{ Encoding = 'ASCII'; Expected = 'QQ==' }
) {
param($Encoding, $Expected)
ConvertTo-Base64String 'A' -Encoding $Encoding | Should -BeExactly $Expected
ConvertFrom-Base64String $Expected -Encoding $Encoding | Should -BeExactly 'A'
}

$result = ConvertFrom-Base64String $encoded
It 'rejects unsupported encodings in both directions' {
{ ConvertTo-Base64String 'text' -Encoding invalid } | Should -Throw
{ ConvertFrom-Base64String 'dGV4dA==' -Encoding invalid } | Should -Throw
}

It 'supports positional UrlSafe, aliases, and multiple pipeline values' {
ConvertTo-Base64String 'text' $true | Should -BeExactly 'dABlAHgAdAA'
$encoded = @('one', 'two' | encode64 -Encoding UTF8)
$encoded.Count | Should -Be 2
$encoded[0] | Should -BeExactly 'b25l'
$encoded[1] | Should -BeExactly 'dHdv'
$decoded = @($encoded | decode64 -Encoding UTF8)
$decoded.Count | Should -Be 2
$decoded[0] | Should -BeExactly 'one'
$decoded[1] | Should -BeExactly 'two'
}

$result | Should -Be $text
It 'produces and decodes both URL-safe substitutions' {
$text = [string][char]0xFBFF
ConvertTo-Base64String $text | Should -BeExactly '//s='
ConvertTo-Base64String $text $true | Should -BeExactly '__s'
ConvertFrom-Base64String '__s' | Should -BeExactly $text
# UTF-8 for U+FFFF contains both + and / in Base64.
$text = [string][char]0xFFFF
ConvertTo-Base64String $text -Encoding UTF8 | Should -BeExactly '77+/'
ConvertTo-Base64String $text -UrlSafe $true -Encoding UTF8 | Should -BeExactly '77-_'
ConvertFrom-Base64String '77-_' -Encoding UTF8 | Should -BeExactly $text
ConvertFrom-Base64String '__s=' | Should -BeExactly ([string][char]0xFBFF)
}
It "Support url safe Base64" {
$encoded="dABlAHgAdAA"
$text="text"

$result = ConvertFrom-Base64String $encoded
It 'accepts padded and unpadded valid input <InputText>' -TestCases @(
@{ InputText = 'Zg=='; Expected = 'f' }
@{ InputText = 'Zg'; Expected = 'f' }
@{ InputText = 'Zm8='; Expected = 'fo' }
@{ InputText = 'Zm8'; Expected = 'fo' }
@{ InputText = 'Zm9v'; Expected = 'foo' }
@{ InputText = " Z g `t`r`n"; Expected = 'f' }
@{ InputText = " Z g = = `r`n"; Expected = 'f' }
@{ InputText = 'dGV4dDE'; Expected = 'text1' }
) {
param($InputText, $Expected)
ConvertFrom-Base64String $InputText -Encoding UTF8 | Should -BeExactly $Expected
}

It 'converts empty strings directly and in pipelines' {
ConvertTo-Base64String '' | Should -BeExactly ''
ConvertFrom-Base64String '' | Should -BeExactly ''
ConvertTo-Base64String '' -Encoding UTF8 | Should -BeExactly ''
ConvertFrom-Base64String '' -Encoding UTF8 | Should -BeExactly ''
$encoded = @('', 'a' | encode64 -Encoding UTF8)
$encoded.Count | Should -Be 2
$encoded[0] | Should -BeExactly ''
$encoded[1] | Should -BeExactly 'YQ=='
$decoded = @('', 'YQ==' | decode64 -Encoding UTF8)
$decoded.Count | Should -Be 2
$decoded[0] | Should -BeExactly ''
$decoded[1] | Should -BeExactly 'a'
ConvertFrom-Base64String " `t`r`n" | Should -BeExactly ''
}

$result | Should -Be $text
It 'rejects malformed Base64 <InputText>' -TestCases @(
@{ InputText = 'A' }
@{ InputText = 'AAAAA' }
@{ InputText = 'Zg=' }
@{ InputText = 'Zm8==' }
@{ InputText = 'Zg======' }
@{ InputText = 'Zm9v====' }
@{ InputText = '====' }
@{ InputText = 'Zg===' }
@{ InputText = '=Zg=' }
@{ InputText = 'Z=g=' }
@{ InputText = 'Zg==AA==' }
@{ InputText = '!!!!' }
@{ InputText = 'Zm$8' }
@{ InputText = ('Zg' + [char]0xA0) }
) {
param($InputText)
{ ConvertFrom-Base64String $InputText } | Should -Throw
}

}
115 changes: 66 additions & 49 deletions Shared-Functions/Base64String/Base64String.ps1
Original file line number Diff line number Diff line change
@@ -1,74 +1,91 @@

<#
.SYNOPSIS
Convert text to Base64 String

Convert text to a Base64 string.
.DESCRIPTION
Encode provided text to Base64 String

Encodes text using Unicode (UTF-16 little-endian) by default, without a byte order mark.
.PARAMETER Value
Value to convert

Text to encode. Accepts pipeline input, including empty strings.
.PARAMETER UrlSafe
Replace + and / with - and _ and omit trailing padding when true.
.PARAMETER Encoding
Text encoding: Unicode (default), UTF8, BigEndianUnicode, UTF32, or ASCII.
Use the same encoding when decoding; Base64 does not record the text encoding.
.EXAMPLE

ConvertFrom-Base64String "dABlAHgAdAA="
echo "dABlAHgAdAA=" | decode64
ConvertTo-Base64String "text"
.EXAMPLE
"text" | encode64 -Encoding UTF8 -UrlSafe $true
#>

Function ConvertTo-Base64String {
param (
[Parameter(Position = 0, ValueFromPipeline = $True)]
[Parameter(Position = 0, ValueFromPipeline = $True)]
[AllowEmptyString()]
[Alias("Text")]
[string]$Value,
[Parameter(Position = 1)]
[bool]$UrlSafe = $false
[bool]$UrlSafe = $false,
[Parameter(Position = 2)]
[ValidateSet('Unicode', 'UTF8', 'BigEndianUnicode', 'UTF32', 'ASCII')]
[string]$Encoding = 'Unicode'
)
$bytes = [System.Text.Encoding]::Unicode.GetBytes($Value)
$encoded = [Convert]::ToBase64String($bytes)
if($UrlSafe){
$encoded = $encoded.TrimEnd('=').Replace('+', '-').Replace('/', '_')
process {
$bytes = [System.Text.Encoding]::$Encoding.GetBytes($Value)
$encoded = [Convert]::ToBase64String($bytes)
if ($UrlSafe) {
$encoded = $encoded.TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
$encoded
}
return $encoded
}


<#
.SYNOPSIS
Convert text from Base 64 String

Convert a Base64 string to text.
.DESCRIPTION
Decode provided text to Base64 String

.PARAMETER Value
Value to convert

Accepts standard or URL-safe Base64, with or without padding. Decodes using
Unicode (UTF-16 little-endian) by default. Malformed Base64 raises an error.
.PARAMETER EncodedValue
Base64 to decode. Accepts pipeline input, including empty strings.
.PARAMETER Encoding
Text encoding: Unicode (default), UTF8, BigEndianUnicode, UTF32, or ASCII.
Must match the encoding used to create the Base64 string.
.EXAMPLE

ConvertFrom-Base64String "text"
echo "text" | decode64
ConvertFrom-Base64String "dABlAHgAdAA="
.EXAMPLE
"dGV4dA" | decode64 -Encoding UTF8
#>
Function ConvertFrom-Base64String {
param (
[Parameter(Position = 0, ValueFromPipeline = $True)]
[string]$EncodedValue
[Parameter(Position = 0, ValueFromPipeline = $True)]
[AllowEmptyString()]
[string]$EncodedValue,
[Parameter(Position = 1)]
[ValidateSet('Unicode', 'UTF8', 'BigEndianUnicode', 'UTF32', 'ASCII')]
[string]$Encoding = 'Unicode'
)

$EncodedValue = $EncodedValue.Replace('_', '/').Replace('-', '+')

if( $EncodedValue.Length%2 -ne 0 ){
$EncodedValue += '='
}

try {
$bytes = [System.Convert]::FromBase64String($EncodedValue)

process {
# Ignore only the whitespace accepted by Convert.FromBase64String.
$normalized = ($EncodedValue -replace '[ \t\r\n]', '').Replace('_', '/').Replace('-', '+')
# Restore padding only for fully unpadded input. Existing padding must
# already be complete; impossible lengths and invalid characters are
# rejected by FromBase64String rather than repaired by a retry.
if (-not $normalized.Contains('=')) {
switch ($normalized.Length % 4) {
2 { $normalized += '==' }
3 { $normalized += '=' }
}
}
# .NET Framework accepts some over-padded input (for example Zm8==)
# that modern .NET rejects. Validate padding shape before either runtime.
if ($normalized.Contains('=') -and
($normalized.Length % 4 -ne 0 -or $normalized -cnotmatch '^[A-Za-z0-9+/]+={1,2}$')) {
throw (New-Object System.FormatException -ArgumentList 'Invalid Base64 length or padding.')
}
try {
$bytes = [System.Convert]::FromBase64String($normalized)
}
catch {
throw
}
[System.Text.Encoding]::$Encoding.GetString($bytes)
}
catch {
$EncodedValue += '=='
$bytes = [System.Convert]::FromBase64String($EncodedValue)
}

$decodedText = [System.Text.Encoding]::Unicode.GetString($bytes)
return $decodedText

}
11 changes: 6 additions & 5 deletions Shared-Functions/Base64String/Base64String.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

@{

ModuleVersion = '1.2.0'
ModuleVersion = '1.3.0'

# ID used to uniquely identify this module
GUID = 'e7bfdc17-9739-4bce-80f3-8eb90d7bc836'
Expand Down Expand Up @@ -44,7 +44,7 @@
Tags = @('Base64String','Base64', 'encode','decode', 'encode64', 'decode64', 'encodeText')

# A URL to the license for this module.
LicenseUri = 'http://opensource.org/licenses/MIT'
LicenseUri = 'http://www.wtfpl.net/txt/copying/'

# A URL to the main website for this project.
ProjectUri = 'https://github.com/stadub/PowershellScripts/tree/master/Shared-Functions/Base64String'
Expand All @@ -54,7 +54,10 @@

# ReleaseNotes of this module
ReleaseNotes = '
* fix decidong ''1'' ending text
* Add explicit text encoding options while preserving Unicode defaults.
* Correct Base64 padding validation on .NET Framework and modern .NET.
* Support empty strings and per-item pipeline conversion.
* Include encoding compatibility regressions for issue #22.
'

}
Expand All @@ -68,5 +71,3 @@
# DefaultCommandPrefix = ''

}


13 changes: 13 additions & 0 deletions Shared-Functions/Base64String/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004

Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.

DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. You just DO WHAT THE FUCK YOU WANT TO.
Loading
Loading