-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheccChaCha.py
More file actions
70 lines (52 loc) · 2.19 KB
/
eccChaCha.py
File metadata and controls
70 lines (52 loc) · 2.19 KB
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
import binascii
import hashlib
import secrets
import os
from Crypto.Cipher import ChaCha20_Poly1305
from tinyec import registry
def encrypt_AES_GCM(msg, secretKey):
"""aesCipher = AES.new(secretKey, AES.MODE_GCM)
ciphertext, authTag = aesCipher.encrypt_and_digest(msg)
return ciphertext, aesCipher.nonce, authTag"""
nonce = os.urandom(12)
chachaCipher = ChaCha20_Poly1305.new(secretKey)
cipherText = chachaCipher.encrypt(nonce, msg)
return cipherText, chachaCipher.nonce
def decrypt_AES_GCM(ciphertext, nonce, secretKey):
"""aesCipher = AES.new(secretKey, AES.MODE_GCM, nonce)
plaintext = aesCipher.decrypt_and_verify(ciphertext, authTag)
return plaintext"""
chachaCipher = ChaCha20_Poly1305.new(secretKey, )
def ecc_point_to_256_bit_key(point):
sha = hashlib.sha256(int.to_bytes(point.x, 32, 'big'))
sha.update(int.to_bytes(point.y, 32, 'big'))
return sha.digest()
curve = registry.get_curve('brainpoolP256r1')
def encrypt_ECC(msg, pubKey):
ciphertextPrivKey = secrets.randbelow(curve.field.n)
sharedECCKey = ciphertextPrivKey * pubKey
secretKey = ecc_point_to_256_bit_key(sharedECCKey)
ciphertext, nonce = encrypt_AES_GCM(msg, secretKey)
ciphertextPubKey = ciphertextPrivKey * curve.g
return ciphertext, nonce, ciphertextPubKey
def decrypt_ECC(encryptedMsg, privKey):
(ciphertext, nonce, authTag, ciphertextPubKey) = encryptedMsg
sharedECCKey = privKey * ciphertextPubKey
secretKey = ecc_point_to_256_bit_key(sharedECCKey)
plaintext = decrypt_AES_GCM(ciphertext, nonce, authTag)
return plaintext
msg = b'Text to be encrypted by ECC public key and ' \
b'decrypted by its corresponding ECC private key'
print("original msg:", msg)
privKey = secrets.randbelow(curve.field.n)
pubKey = privKey * curve.g
encryptedMsg = encrypt_ECC(msg, pubKey)
encryptedMsgObj = {
'ciphertext': binascii.hexlify(encryptedMsg[0]),
'nonce': binascii.hexlify(encryptedMsg[1]),
'authTag': binascii.hexlify(encryptedMsg[2]),
'ciphertextPubKey': hex(encryptedMsg[3].x) + hex(encryptedMsg[3].y % 2)[2:]
}
print("encrypted msg:", encryptedMsgObj)
decryptedMsg = decrypt_ECC(encryptedMsg, privKey)
print("decrypted msg:", decryptedMsg)