Skip to content

Commit 941ec46

Browse files
authored
Add Base64 Encode Decode in Tcl (#5006)
1 parent a674d1e commit 941ec46

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env tclsh
2+
3+
proc usage {} {
4+
puts stderr "Usage: please provide a mode and a string to encode/decode"
5+
exit 1
6+
}
7+
8+
if {$argc != 2} {
9+
usage
10+
}
11+
12+
set mode [lindex $argv 0]
13+
set text [lindex $argv 1]
14+
15+
if {$text eq ""} {
16+
usage
17+
}
18+
19+
20+
switch -- $mode {
21+
encode {
22+
set result [binary encode base64 $text]
23+
}
24+
decode {
25+
if {[catch {binary decode base64 $text} result]} {
26+
usage
27+
}
28+
# Tcl’s decoder sometimes tolerates invalid padding, so validate manually
29+
# Check that input length is a multiple of 4 and only contains valid chars
30+
if {![regexp {^[A-Za-z0-9+/]*={0,2}$} $text]} {
31+
usage
32+
}
33+
if {[expr {[string length $text] % 4 != 0}]} {
34+
usage
35+
}
36+
}
37+
default {
38+
usage
39+
}
40+
}
41+
42+
puts $result
43+

0 commit comments

Comments
 (0)