Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
all-algorithms-python/ciphers/base64.py at bubble_sort · UnixJunkie/all-algorithms-python · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
UnixJunkie
/
all-algorithms-python
Public
forked from
TheAlgorithms/Python
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Files
Expand file tree
bubble_sort
Breadcrumbs
all-algorithms-python
/
ciphers
/
base64.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
142 lines (118 loc) · 4.9 KB
bubble_sort
Breadcrumbs
all-algorithms-python
/
ciphers
/
base64.py
Copy path
Top
File metadata and controls
Code
Blame
142 lines (118 loc) · 4.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
B64_CHARSET
=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def
base64_encode
(
data
:
bytes
)
->
bytes
:
"""Encodes data according to RFC4648.
The data is first transformed to binary and appended with binary digits so that its
length becomes a multiple of 6, then each 6 binary digits will match a character in
the B64_CHARSET string. The number of appended binary digits would later determine
how many "=" signs should be added, the padding.
For every 2 binary digits added, a "=" sign is added in the output.
We can add any binary digits to make it a multiple of 6, for instance, consider the
following example:
"AA" -> 0010100100101001 -> 001010 010010 1001
As can be seen above, 2 more binary digits should be added, so there's 4
possibilities here: 00, 01, 10 or 11.
That being said, Base64 encoding can be used in Steganography to hide data in these
appended digits.
>>> from base64 import b64encode
>>> a = b"This pull request is part of Hacktoberfest20!"
>>> b = b"https://tools.ietf.org/html/rfc4648"
>>> c = b"A"
>>> base64_encode(a) == b64encode(a)
True
>>> base64_encode(b) == b64encode(b)
True
>>> base64_encode(c) == b64encode(c)
True
>>> base64_encode("abc")
Traceback (most recent call last):
...
TypeError: a bytes-like object is required, not 'str'
"""
# Make sure the supplied data is a bytes-like object
if
not
isinstance
(
data
,
bytes
):
raise
TypeError
(
f"a bytes-like object is required, not '
{
data
.
__class__
.
__name__
}
'"
)
binary_stream
=
""
.
join
(
bin
(
byte
)[
2
:].
zfill
(
8
)
for
byte
in
data
)
padding_needed
=
len
(
binary_stream
)
%
6
!=
0
if
padding_needed
:
# The padding that will be added later
padding
=
b"="
*
((
6
-
len
(
binary_stream
)
%
6
)
//
2
)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream
+=
"0"
*
(
6
-
len
(
binary_stream
)
%
6
)
else
:
padding
=
b""
# Encode every 6 binary digits to their corresponding Base64 character
return
(
""
.
join
(
B64_CHARSET
[
int
(
binary_stream
[
index
:
index
+
6
],
2
)]
for
index
in
range
(
0
,
len
(
binary_stream
),
6
)
).
encode
()
+
padding
)
def
base64_decode
(
encoded_data
:
str
)
->
bytes
:
"""Decodes data according to RFC4648.
This does the reverse operation of base64_encode.
We first transform the encoded data back to a binary stream, take off the
previously appended binary digits according to the padding, at this point we
would have a binary stream whose length is multiple of 8, the last step is
to convert every 8 bits to a byte.
>>> from base64 import b64decode
>>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh"
>>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg="
>>> c = "QQ=="
>>> base64_decode(a) == b64decode(a)
True
>>> base64_decode(b) == b64decode(b)
True
>>> base64_decode(c) == b64decode(c)
True
>>> base64_decode("abc")
Traceback (most recent call last):
...
AssertionError: Incorrect padding
"""
# Make sure encoded_data is either a string or a bytes-like object
if
not
isinstance
(
encoded_data
,
bytes
)
and
not
isinstance
(
encoded_data
,
str
):
raise
TypeError
(
"argument should be a bytes-like object or ASCII string, not "
f"'
{
encoded_data
.
__class__
.
__name__
}
'"
)
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
if
isinstance
(
encoded_data
,
bytes
):
try
:
encoded_data
=
encoded_data
.
decode
(
"utf-8"
)
except
UnicodeDecodeError
:
raise
ValueError
(
"base64 encoded data should only contain ASCII characters"
)
padding
=
encoded_data
.
count
(
"="
)
# Check if the encoded string contains non base64 characters
if
padding
:
assert
all
(
char
in
B64_CHARSET
for
char
in
encoded_data
[:
-
padding
]
),
"Invalid base64 character(s) found."
else
:
assert
all
(
char
in
B64_CHARSET
for
char
in
encoded_data
),
"Invalid base64 character(s) found."
# Check the padding
assert
len
(
encoded_data
)
%
4
==
0
and
padding
<
3
,
"Incorrect padding"
if
padding
:
# Remove padding if there is one
encoded_data
=
encoded_data
[:
-
padding
]
binary_stream
=
""
.
join
(
bin
(
B64_CHARSET
.
index
(
char
))[
2
:].
zfill
(
6
)
for
char
in
encoded_data
)[:
-
padding
*
2
]
else
:
binary_stream
=
""
.
join
(
bin
(
B64_CHARSET
.
index
(
char
))[
2
:].
zfill
(
6
)
for
char
in
encoded_data
)
data
=
[
int
(
binary_stream
[
index
:
index
+
8
],
2
)
for
index
in
range
(
0
,
len
(
binary_stream
),
8
)
]
return
bytes
(
data
)
if
__name__
==
"__main__"
:
import
doctest
doctest
.
testmod
()
You can’t perform that action at this time.