Cryptography
Identifying the type of cipher text
and the encryption algorithm
This is very important if you encountered a cipher
text and don't know what is the encryption
algorithm.
https://www.boxentriq.com/code-
breaking/cipher-identifier
OpenSSL
Deciphering an encrypted file with
OpenSSL
root@kali:openssl enc -d –[algorithm-name]
-in salary_dec2003.csv.enc -out
salary_dec2003.csv -k [password]
Algorithm names for openssl:
<root@kali:openssl enc help>
Decrypting RSA key
openssl rsa -in [encrypted-key] -out
[key_decrypted]
You may need the passphrase to decrypt the RSA
key.
Decrypting VNC viewer password
Download the vnc decrypter below
https://github.com/jeroennijhof/vncpwd
Compile it
gcc -Wall -g -o vncpwd vncpwd.c d3des.c
Run it
./vncpwd [vnc passfile]
Vigenere Ciphers
Decrypting Vigenere Ciphers
To decrypt a vigenere message, we need the
cipher text and the key used to decrypt it. Then we
can use the below online service
http://rumkin.com/tools/cipher/vigenere-
keyed.php
Another resource
https://www.boxentriq.com/code-
breaking/vigenere-cipher
Oracle Padding Attack
#Oracle padding attacks are common when a web
application uses parameter query string to store
encrypted values such as username,id or company
id.
#A padding attack can be detected when you find
that query parameter and send an unexpected
input. The browser will return [invalid padding].
That's when you know a padding attack is possible
to decrypt the content stored in the query
parameter.
#Example is using a query parameter to store
authorization information such as the username. An
example query parameter is below
cookie: auth=[encrypted-value]
#PadBuster is a tool used to decrypt such values
https://github.com/AonCyberLabs/PadBuster
#Usage
padbuster URL EncryptedSample BlockSize
[options]
#By default, block size in oracle is 8 byte].
Example usage is below
padbuster http://domain.com [encrypted-
value] 8 -cookies auth=[encrypted-value] -
-encoding
#This will give you the decrypted value. In this
case it's the username you are assigned to. You
can then modify on the command to give you the
encrypted value for another user,say its[admin]
padbuster http://domain.com [encrypted-
value] 8 -cookies auth=[encrypted-value] -
plaintext user=admin
#The output of this is an encrypted value which
you can use to replace the current value of [auth].
You can do this during a Burp suite intercept
request and then you will be able to log in as that
user.
The substitute cipher
Its called the substitute cipher as it contains
repeated patthers. Ofteh these ciphers are found in
newspapers puzzles. An example is below
Szszsz! Mlylwb droo tfvhh nb mvd kzhhdliw!
Lmob z uvd ofxpb hlfoh szev Vhxzkvw uiln
Zoxzgiza zorev orpv R wrw!!!
In this example, the repeated pattern or characters
are Szszsz]. We can decrypt substitute ciphers
using the tool in the link below
https://quipqiup.com/
Elliptic Curve Cryptography
Algorithm
ECC algoritim is a kind of public key cryptography
that allows for smaller keys and low power
requirements. So it works by generating a public
and private keys. The public key is used in
encrypting your message and to decrypt it you
need your private key.
Example of generating a keypair
$ seccure-key
This will enter a prompt like below
Assuming curve p160.
Enter private key: [your-private-key]
The public key is:
8W;>i^H0qi|J&$coR5MFpR*Vn
#Encryption : the below command lets you create
a message, encrypt it and send it to an output file
[encrypted.msg]
seccure-encrypt -o encrypted.msg 'your-
public-key'
This will generate the below prompt at which you
will type your private message you wish to encrypt.
Assuming MAC length of 80 bits.
Go ahead and type your message ...
[type your message here]
#Decryption : you can decrypt the same message
using the below command
seccure-decrypt -i encrypted.msg
The above command will prompt you to enter the
[private key].
#Decryption with python: You can integrate the
above tool with python for derypting a cipher text
import seccure
cipher = "\x01\xd3\xe1\xf2\x17T
\xd0\x8a\xd6\xe2\xbd\x9e\x9e~P(\xf7\xe9\xa
5\xc1KT\x9aI\xdd\\!\x95t\xe1\xd6p\xaa\"u2\
xc2\x85F\x1e\xbc\x00\xb9\x17\x97\xb8\x0b\x
c5y\xec<K-
gp9\xa0\xcb\xac\x9et\x89z\x13\x15\x94Dn\xe
b\x95\x19[\x80\xf1\xa8,\x82G`\xee\xe8C\xc1
\x15\xa1~T\x07\xcc{\xbd\xda\xf0\x9e\x1bh\'
QU\xe7\x163\xd4F\xcc\xc5\x99w"
print seccure.decrypt(cipher, "the-
private-key")
More info about the tool can be found here
[http://point-at-infinity.org/seccure/]
RSA Encryption
Decrypting a basic private key
id_rsa.crypt
Note that you can use RSACTFtool] as
alternative method to the below one
In RSA, there is the public key which is two number
[n] and [e] and there is the private key which is
also two numbers [n] and [d]. [n] is the product of
two large prime numbers [p] and [q]. In decrypting
private keys, we need to calculate the [d].
In python, you can do that with the [pow] function
as below
d = pow(key.e, -1, (p-1)*(q-1))
But first we have to calculate [n] , [e] , [p] , [q].
In python if you have the public key [key.pub] you
can find [n] and [e] using python interpreter
>>> from Crypto.PublicKey import RSA
>>> with open('key.pub', 'r') as f:
key = RSA.importKey(f.read())
>>> key.n
>>> key.e
Then you can use the value of [n] and input it in
this site [http://factordb.com/index.php]
it will calculate [p] and [q].
Then we can start the decryption process with
python3
>>> with open('id_rsa.crypt', 'rb') as f:
dc = f.read()
>>> int.from_bytes(ct, byteorder='rsa')
>>> pow(int.from_bytes(ct, 'rsa'), d,
key.n)
>>> pow(int.from_bytes(ct, 'rsa'), d,
key.n).to_bytes(32, 'rsa')
This will give you the password for the private RSA
key.
Encrypting a password/message
from an input text file using python
and sage library
The below script takes the text in [plaintext.txt file]
and using mathmetical calculations with [sage]
library it calculates the encrypted text and stores it
in [cipertext.txt]
nbits = 1024
password =
open("plaintext.txt").read().strip()
enc_pass = open("ciphertext.txt","w")
debug = open("log.txt","w")
m =
Integer(int(password.encode('hex'),16))
p = random_prime(2^floor(nbits/2)-1,
lbound=2^floor(nbits/2-1), proof=False)
q = random_prime(2^floor(nbits/2)-1,
lbound=2^floor(nbits/2-1), proof=False)
n = p*q
phi = (p-1)*(q-1)
e = ZZ.random_element(phi)
while gcd(e, phi) != 1:
e = ZZ.random_element(phi)
c = pow(m, e, n)
enc_pass.write('Encrypted Text:
'+str(c)+'\n')
debug.write(str(p)+'\n')
debug.write(str(q)+'\n')
debug.write(str(e)+'\n')
Below is an example of how to decrypt the exact
same cipher text created above.
Recover an RSA encrypted
message/password/key with the
Extended Euclidean Algorithm
This method relies on the availability of certain
variables
[p,q,e]. These variables are calculated during the
encryption process.
If you happen to have access to the encryption
script then see if you can find the file storing these
values.
Below is an authored script to achieve that
purpose. You can also find it with the link
here[https://gist.github.com/intrd/3f6e8f02e16faa5
4729b9288a8f59582
#!/usr/bin/python
## RSA - Given p,q and e.. recover and use
private key w/ Extended Euclidean
Algorithm - crypto150-
what_is_this_encryption @ alexctf 2017
# @author intrd - http://dann.com.br/
(original script here:
http://crypto.stackexchange.com/questions/
19444/rsa-given-q-p-and-e)
# @license Creative Commons Attribution-
ShareAlike 4.0 International License -
http://creativecommons.org/licenses/by-
sa/4.0/
import binascii, base64
p =
0xa6055ec186de51800ddd6fcbf0192384ff42d707
a55f57af4fcfb0d1dc7bd97055e8275cd4b78ec63c
5d592f567c66393a061324aa2e6a8d8fc2a910cbee
1ed9
q =
0xfa0f9463ea0a93b929c099320d31c277e0b0dbc6
5b189ed76124f5a1218f5d91fd0102a4c8de11f28b
e5e4d0ae91ab319f4537e97ed74bc663e972a4a911
9307
e =
0x6d1fdab4ce3217b3fc32c9ed480a31d067fd57d9
3a9ab52b472dc393ab7852fbcb11abbebfd6aaae80
32db1316dc22d3f7c3d631e24df13ef23d3b381a1c
3e04abcc745d402ee3a031ac2718fae63b240837b4
f657f29ca4702da9af22a3a019d68904a969ddb01b
cf941df70af042f4fae5cbeb9c2151b324f387e525
094c41
ct =
0x7fe1a4f743675d1987d25d38111fae0f78bbea68
52cba5beda47db76d119a3efe24cb04b9449f53bec
d43b0b46e269826a983f832abb53b7a7e24a43ad15
378344ed5c20f51e268186d24c76050c1e73647523
bd5f91d9b6ad3e86bbf9126588b1dee21e6997372e
36c3e74284734748891829665086e0dc523ed23c38
6bb520
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
n = p*q #product of primes
phi = (p-1)*(q-1) #modular multiplicative
inverse
gcd, a, b = egcd(e, phi) #calling extended
euclidean algorithm
d = a #a is decryption key
out = hex(d)
print("d_hex: " + str(out));
print("n_dec: " + str(d));
pt = pow(ct, d, n)
print("pt_dec: " + str(pt))
out = hex(pt)
out = str(out[2:-1])
print "flag"
print out.decode("hex")
Don't forget to replace [p,q,e] with the values you
have. For [ct] it's the cipher text which needs
decryption.
Deciphering weak public key
encryption:
Normally weak public keys have short encryption
keys with .crypt file extesntion. Lets say we have
two files
Key.pub
Pass.crypt
We would attempt decrypting the public key and
extract the password of the private key with the
below command
root@kali:./RsaCtfTool.py --publickey
/root/Desktop/key.pub --uncipherfile
/root/Desktop/pass.crypt
Decrypting firefox profile passwords
We can use the tool in the below URL and clone it
https://github.com/unode/firefox_decrypt
Then run it after specifying the path of the profile
python3 firefox.decrypt.py <Path-to-
profile>
All firefox profiles are stored under the
[firefox/profiles] directory.
ROT13 Algorithm
Manual encryption and decryption
Encrypt a string [test]
echo "test" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
Decrypt a string Guvf vf n Grfg]
echo "Guvf vf n Grfg" | tr 'A-Za-z' 'N-ZA-
Mn-za-m'
Using Tools
https://rot13.com/
Steganography
Image steganography
Decoding payloads in JPEG,WAV or
AU files
https://futureboy.us/stegano/decinput.html
Using steghide to extract hidden
content
steghide extract -sf [file]
Using binwalk to view and extract
hidden content
binwalk image.png
binwalk -e image.png
Viewing hidden details
https://29a.ch/photo-forensics/#strings
https://futureboy.us/stegano/decinput.html
Note
Sometimes the image is protected by a passphrase
which you need to supply in order to extract the
hidden information.
You can use the below script to brute force the
password and reveal the hidden files
for word in $(cat $2); do
steghide extract -sf $1 -p $word &>
/dev/null
if [ $? == 0 ]; then
echo
echo "[!] Password Found - $word [!]"
break
else
echo "Password Couldn't be found. Use a
different wordlist - $word"
fi
done
Run the script
script.sh image.png wordlist.txt
Audio Steganography
Images can be encoded inside audio files with a
technique called [spectrogram]. Using Audio
visualizer] or [Sonic Visualizer] we can decode
images encoded inside Audio files.
Before doing that lets first understand the process
of Spectrology] which is converting or encoding
images to audio files. The python script below can
be used to encode images into audio files. Script
author is
[https://github.com/solusipse/spectrology]
#!/usr/bin/env python
'''
Spectrology
This script is able to encode an image
into audio file whose spectrogram
represents input image.
License: MIT
Website:
https://github.com/solusipse/spectrology
'''
from PIL import Image, ImageOps
import wave, math, array, argparse, sys,
timeit
def parser():
parser = argparse.ArgumentParser()
parser.add_argument("INPUT", help="Name of
the image to be convected.")
parser.add_argument("-r", "--rotate",
help="Rotate image 90 degrees for
waterfall spectrographs.",
action='store_true')
parser.add_argument("-i", "--invert",
help="Invert image colors.",
action='store_true')
parser.add_argument("-o", "--output",
help="Name of the output wav file. Default
value: out.wav).")
parser.add_argument("-b", "--bottom",
help="Bottom frequency range. Default
value: 200.", type=int)
parser.add_argument("-t", "--top",
help="Top frequency range. Default value:
20000.", type=int)
parser.add_argument("-p", "--pixels",
help="Pixels per second. Default value:
30.", type=int)
parser.add_argument("-s", "--sampling",
help="Sampling rate. Default value:
44100.", type=int)
args = parser.parse_args()
minfreq = 200
maxfreq = 20000
wavrate = 44100
pxs = 30
output = "out.wav"
rotate = False
invert = False
if args.output:
output = args.output
if args.bottom:
minfreq = args.bottom
if args.top:
maxfreq = args.top
if args.pixels:
pxs = args.pixels
if args.sampling:
wavrate = args.sampling
if args.rotate:
rotate = True
if args.invert:
invert = True
print('Input file: %s.' % args.INPUT)
print('Frequency range: %d - %d.' %
(minfreq, maxfreq))
print('Pixels per second: %d.' % pxs)
print('Sampling rate: %d.' % wavrate)
print('Rotate Image: %s.' % ('yes' if
rotate else 'no'))
return (args.INPUT, output, minfreq,
maxfreq, pxs, wavrate, rotate, invert)
def convert(inpt, output, minfreq,
maxfreq, pxs, wavrate, rotate, invert):
img = Image.open(inpt).convert('L')
# rotate image if requested
if rotate:
img = img.rotate(90)
# invert image if requested
if invert:
img = ImageOps.invert(img)
output = wave.open(output, 'w')
output.setparams((1, 2, wavrate, 0,
'NONE', 'not compressed'))
freqrange = maxfreq - minfreq
interval = freqrange / img.size[1]
fpx = wavrate // pxs
data = array.array('h')
tm = timeit.default_timer()
for x in range(img.size[0]):
row = []
for y in range(img.size[1]):
yinv = img.size[1] - y - 1
amp = img.getpixel((x,y))
if (amp > 0):
row.append( genwave(yinv * interval +
minfreq, amp, fpx, wavrate) )
for i in range(fpx):
for j in row:
try:
data[i + x * fpx] += j[i]
except(IndexError):
data.insert(i + x * fpx, j[i])
except(OverflowError):
if j[i] > 0:
data[i + x * fpx] = 32767
else:
data[i + x * fpx] = -32768
sys.stdout.write("Conversion progress:
%d%% \r" % (float(x) / img.size[0]*100) )
sys.stdout.flush()
output.writeframes(data.tostring())
output.close()
tms = timeit.default_timer()
print("Conversion progress: 100%")
print("Success. Completed in %d seconds."
% int(tms-tm))
def genwave(frequency, amplitude, samples,
samplerate):
cycles = samples * frequency / samplerate
a = []
for i in range(samples):
x = math.sin(float(cycles) * 2 * math.pi *
i / float(samples)) * float(amplitude)
a.append(int(math.floor(x)))
return a
if __name__ == '__main__':
inpt = parser()
convert(*inpt)
The script runs by providing an input image, top
frequency range and bottom frequency range
python spectrology.py test.bmp -b 13000 -t
19000 -o test.wav
The output will be an audio file. Likewise if we want
to view the image inside this audio file we will need
the help of Audio visualizer]. The below figure
shows the image after opening the file with Audio
Visualizer]
Encoding and Decoding
The Ook! Language
................!?!!.?................?.?!
.?............................!.?.........
..!?!!.?..........?.?!.?................!.
..........!.?.......!?!!.?!!!!!!?.?!.?!!!!
!!!...!...........!.!!!!!!!!!!!!!!!.?.....
............!?!!.?!!!!!!!!!!!!!!!!?.?!.?!!
!!!!!!!!!!!!!.?.................!?!!.?....
............?.?!.?................!.!!!!!!
!.?.......!?!!.?......?.?!
Decode Ook! with
https://www.dcode.fr/ook-language
The Brainfuck
+++++ +++++ [->++ +++++ +++<] >++++ +.---
--.++ +++++ .<+++ [->++ +<]>+ ++.<+ ++[->
---<] >---- --.-- ----- .<+++ +[->+ +++<]
>+++. <+++[ ->--- <]>-- .<+++ [->++ +<]>+
.---. <+++[ ->--- <]>-- ----. <++++ [->++
++<]> ++..<
Decode with
https://copy.sh/brainfuck/
https://www.dcode.fr/ook-language
Base64 Decoding and Encoding
Automated script to encode and
decode to and from base64
The assumption in the below command is that the
base64 string is in a file named [example]. We can
choose how many times to encode the string. The
below example encode the string in the text file 10
times
data=$(cat example); for i in $(seq 1 10);
do data=$(echo $data | tr -d ' ' |
base64); done; echo $data
And likewise we can decode the output. You can
store the output in a file named [file.b64
data=$(cat file.b64); for i in $(seq 1
10); do data=$(echo $data | tr -d ' ' |
base64 -d); done; echo $data
Hex Decoding and Encoding
Encoding text to hex
echo -n "Insert-text-here" | xxd
Encoding hex to binary
echo insert-hex-here | xxd -r -p
Resources
Encoding and Decoding
https://gchq.github.io/CyberChef/
https://www.dcode.fr/en
Hashing
MD5
Generating md5 checksum for a file
md5sum file
SHA1
Generating SHA1 checksum for a file
$ sha1sum file
$ shasum file
$ shasum file
SHA256 and 512
Generating SHA256 and 512
checksum for a file
shasum -a256 file
Likewise for 512 checksum
shasum -a512 file