2018-02-01 22:45:15 +00:00
|
|
|
'''
|
|
|
|
Onionr - P2P Microblogging Platform & Social network
|
|
|
|
|
|
|
|
This file handles Onionr's cryptography.
|
|
|
|
'''
|
|
|
|
'''
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
|
|
it under the terms of the GNU General Public License as published by
|
|
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
|
|
(at your option) any later version.
|
|
|
|
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
GNU General Public License for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License
|
|
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
'''
|
2018-06-15 05:45:07 +00:00
|
|
|
import nacl.signing, nacl.encoding, nacl.public, nacl.hash, nacl.secret, os, binascii, base64, hashlib, logger, onionrproofs, time, math, sys
|
|
|
|
|
|
|
|
# secrets module was added into standard lib in 3.6+
|
|
|
|
if sys.version_info[0] == 3 and sys.version_info[1] < 6:
|
|
|
|
from dependencies import secrets
|
|
|
|
elif sys.version_info[0] == 3 and sys.version_info[1] >= 6:
|
|
|
|
import secrets
|
2018-02-01 22:45:15 +00:00
|
|
|
|
|
|
|
class OnionrCrypto:
|
2018-02-07 09:04:58 +00:00
|
|
|
def __init__(self, coreInstance):
|
|
|
|
self._core = coreInstance
|
2018-02-21 02:44:56 +00:00
|
|
|
self._keyFile = 'data/keys.txt'
|
2018-05-07 06:55:03 +00:00
|
|
|
self.keyPowFile = 'data/keyPow.txt'
|
2018-02-21 02:44:56 +00:00
|
|
|
self.pubKey = None
|
|
|
|
self.privKey = None
|
2018-05-13 03:45:32 +00:00
|
|
|
|
2018-06-15 05:45:07 +00:00
|
|
|
self.secrets = secrets
|
|
|
|
|
2018-05-07 06:55:03 +00:00
|
|
|
self.pubKeyPowToken = None
|
2018-05-15 04:24:38 +00:00
|
|
|
#self.pubKeyPowHash = None
|
2018-05-07 06:55:03 +00:00
|
|
|
|
2018-04-25 04:04:12 +00:00
|
|
|
self.HASH_ID_ROUNDS = 2000
|
2018-02-21 02:44:56 +00:00
|
|
|
|
|
|
|
# Load our own pub/priv Ed25519 keys, gen & save them if they don't exist
|
|
|
|
if os.path.exists(self._keyFile):
|
|
|
|
with open('data/keys.txt', 'r') as keys:
|
|
|
|
keys = keys.read().split(',')
|
|
|
|
self.pubKey = keys[0]
|
|
|
|
self.privKey = keys[1]
|
2018-05-07 06:55:03 +00:00
|
|
|
try:
|
|
|
|
with open(self.keyPowFile, 'r') as powFile:
|
|
|
|
data = powFile.read()
|
2018-05-15 04:24:38 +00:00
|
|
|
self.pubKeyPowToken = data
|
2018-05-07 06:55:03 +00:00
|
|
|
except (FileNotFoundError, IndexError):
|
|
|
|
pass
|
2018-02-21 02:44:56 +00:00
|
|
|
else:
|
|
|
|
keys = self.generatePubKey()
|
|
|
|
self.pubKey = keys[0]
|
|
|
|
self.privKey = keys[1]
|
|
|
|
with open(self._keyFile, 'w') as keyfile:
|
|
|
|
keyfile.write(self.pubKey + ',' + self.privKey)
|
2018-05-07 06:55:03 +00:00
|
|
|
with open(self.keyPowFile, 'w') as keyPowFile:
|
2018-07-09 07:02:33 +00:00
|
|
|
proof = onionrproofs.DataPOW(self.pubKey)
|
2018-05-07 06:55:03 +00:00
|
|
|
logger.info('Doing necessary work to insert our public key')
|
|
|
|
while True:
|
|
|
|
time.sleep(0.2)
|
|
|
|
powToken = proof.getResult()
|
|
|
|
if powToken != False:
|
|
|
|
break
|
|
|
|
keyPowFile.write(base64.b64encode(powToken[1]).decode())
|
|
|
|
self.pubKeyPowToken = powToken[1]
|
|
|
|
self.pubKeyPowHash = powToken[0]
|
2018-02-21 02:44:56 +00:00
|
|
|
return
|
|
|
|
|
2018-04-26 19:56:17 +00:00
|
|
|
def edVerify(self, data, key, sig, encodedData=True):
|
2018-03-01 19:59:07 +00:00
|
|
|
'''Verify signed data (combined in nacl) to an ed25519 key'''
|
2018-04-27 02:14:31 +00:00
|
|
|
try:
|
|
|
|
key = nacl.signing.VerifyKey(key=key, encoder=nacl.encoding.Base32Encoder)
|
2018-04-27 02:18:17 +00:00
|
|
|
except nacl.exceptions.ValueError:
|
2018-04-27 02:14:31 +00:00
|
|
|
logger.warn('Signature by unknown key (cannot reverse hash)')
|
|
|
|
return False
|
2018-04-26 19:56:17 +00:00
|
|
|
retData = False
|
|
|
|
sig = base64.b64decode(sig)
|
2018-04-27 01:15:30 +00:00
|
|
|
try:
|
|
|
|
data = data.encode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2018-04-26 19:56:17 +00:00
|
|
|
if encodedData:
|
|
|
|
try:
|
|
|
|
retData = key.verify(data, sig) # .encode() is not the same as nacl.encoding
|
|
|
|
except nacl.exceptions.BadSignatureError:
|
|
|
|
pass
|
2018-03-01 19:59:07 +00:00
|
|
|
else:
|
2018-04-26 19:56:17 +00:00
|
|
|
try:
|
|
|
|
retData = key.verify(data, sig)
|
|
|
|
except nacl.exceptions.BadSignatureError:
|
|
|
|
pass
|
2018-03-01 19:59:07 +00:00
|
|
|
return retData
|
2018-05-13 03:45:32 +00:00
|
|
|
|
2018-03-01 19:59:07 +00:00
|
|
|
def edSign(self, data, key, encodeResult=False):
|
|
|
|
'''Ed25519 sign data'''
|
2018-04-26 19:56:17 +00:00
|
|
|
try:
|
|
|
|
data = data.encode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2018-03-01 19:59:07 +00:00
|
|
|
key = nacl.signing.SigningKey(seed=key, encoder=nacl.encoding.Base32Encoder)
|
|
|
|
retData = ''
|
|
|
|
if encodeResult:
|
2018-04-26 19:56:17 +00:00
|
|
|
retData = key.sign(data, encoder=nacl.encoding.Base64Encoder).signature.decode() # .encode() is not the same as nacl.encoding
|
2018-03-01 19:59:07 +00:00
|
|
|
else:
|
2018-04-26 19:56:17 +00:00
|
|
|
retData = key.sign(data).signature
|
2018-03-01 19:59:07 +00:00
|
|
|
return retData
|
|
|
|
|
2018-06-20 07:40:49 +00:00
|
|
|
def pubKeyEncrypt(self, data, pubkey, anonymous=True, encodedData=False):
|
2018-03-16 20:38:33 +00:00
|
|
|
'''Encrypt to a public key (Curve25519, taken from base32 Ed25519 pubkey)'''
|
|
|
|
retVal = ''
|
2018-04-02 00:33:09 +00:00
|
|
|
|
2018-07-13 21:02:41 +00:00
|
|
|
try:
|
|
|
|
pubkey = pubkey.encode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
2018-04-02 00:33:09 +00:00
|
|
|
if encodedData:
|
|
|
|
encoding = nacl.encoding.Base64Encoder
|
|
|
|
else:
|
|
|
|
encoding = nacl.encoding.RawEncoder
|
|
|
|
|
2018-03-16 20:38:33 +00:00
|
|
|
if self.privKey != None and not anonymous:
|
2018-04-26 19:56:17 +00:00
|
|
|
ownKey = nacl.signing.SigningKey(seed=self.privKey, encoder=nacl.encoding.Base32Encoder)
|
2018-03-16 20:38:33 +00:00
|
|
|
key = nacl.signing.VerifyKey(key=pubkey, encoder=nacl.encoding.Base32Encoder).to_curve25519_public_key()
|
|
|
|
ourBox = nacl.public.Box(ownKey, key)
|
2018-04-02 00:33:09 +00:00
|
|
|
retVal = ourBox.encrypt(data.encode(), encoder=encoding)
|
2018-03-16 20:38:33 +00:00
|
|
|
elif anonymous:
|
|
|
|
key = nacl.signing.VerifyKey(key=pubkey, encoder=nacl.encoding.Base32Encoder).to_curve25519_public_key()
|
|
|
|
anonBox = nacl.public.SealedBox(key)
|
2018-07-13 21:02:41 +00:00
|
|
|
try:
|
|
|
|
data = data.encode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
retVal = anonBox.encrypt(data, encoder=encoding)
|
2018-03-16 20:38:33 +00:00
|
|
|
return retVal
|
2018-02-21 02:44:56 +00:00
|
|
|
|
2018-04-18 03:43:33 +00:00
|
|
|
def pubKeyDecrypt(self, data, pubkey='', anonymous=False, encodedData=False):
|
2018-02-21 02:44:56 +00:00
|
|
|
'''pubkey decrypt (Curve25519, taken from Ed25519 pubkey)'''
|
2018-04-18 03:43:33 +00:00
|
|
|
retVal = False
|
2018-04-02 00:33:09 +00:00
|
|
|
if encodedData:
|
|
|
|
encoding = nacl.encoding.Base64Encoder
|
|
|
|
else:
|
|
|
|
encoding = nacl.encoding.RawEncoder
|
2018-04-18 03:43:33 +00:00
|
|
|
ownKey = nacl.signing.SigningKey(seed=self.privKey, encoder=nacl.encoding.Base32Encoder()).to_curve25519_private_key()
|
|
|
|
if self.privKey != None and not anonymous:
|
2018-04-02 00:33:09 +00:00
|
|
|
ourBox = nacl.public.Box(ownKey, pubkey)
|
|
|
|
decrypted = ourBox.decrypt(data, encoder=encoding)
|
|
|
|
elif anonymous:
|
|
|
|
anonBox = nacl.public.SealedBox(ownKey)
|
2018-04-18 03:43:33 +00:00
|
|
|
decrypted = anonBox.decrypt(data, encoder=encoding)
|
2018-04-02 00:33:09 +00:00
|
|
|
return decrypted
|
2018-02-04 03:44:29 +00:00
|
|
|
|
2018-04-02 00:33:09 +00:00
|
|
|
def symmetricPeerEncrypt(self, data, peer):
|
|
|
|
'''Salsa20 encrypt data to peer (with mac)
|
|
|
|
this function does not accept a key, it is a wrapper for encryption with a peer
|
|
|
|
'''
|
|
|
|
key = self._core.getPeerInfo(4)
|
|
|
|
if type(key) != bytes:
|
|
|
|
key = self._core.getPeerInfo(2)
|
|
|
|
encrypted = self.symmetricEncrypt(data, key, encodedKey=True)
|
|
|
|
return encrypted
|
2018-02-04 03:44:29 +00:00
|
|
|
|
2018-02-21 02:44:56 +00:00
|
|
|
def symmetricPeerDecrypt(self, data, peer):
|
2018-04-02 00:33:09 +00:00
|
|
|
'''Salsa20 decrypt data from peer (with mac)
|
|
|
|
this function does not accept a key, it is a wrapper for encryption with a peer
|
|
|
|
'''
|
|
|
|
key = self._core.getPeerInfo(4)
|
|
|
|
if type(key) != bytes:
|
|
|
|
key = self._core.getPeerInfo(2)
|
|
|
|
decrypted = self.symmetricDecrypt(data, key, encodedKey=True)
|
|
|
|
return decrypted
|
|
|
|
|
|
|
|
def symmetricEncrypt(self, data, key, encodedKey=False, returnEncoded=True):
|
|
|
|
'''Encrypt data to a 32-byte key (Salsa20-Poly1305 MAC)'''
|
|
|
|
if encodedKey:
|
|
|
|
encoding = nacl.encoding.Base64Encoder
|
|
|
|
else:
|
|
|
|
encoding = nacl.encoding.RawEncoder
|
|
|
|
|
|
|
|
# Make sure data is bytes
|
|
|
|
if type(data) != bytes:
|
|
|
|
data = data.encode()
|
|
|
|
|
|
|
|
box = nacl.secret.SecretBox(key, encoder=encoding)
|
|
|
|
|
|
|
|
if returnEncoded:
|
|
|
|
encoding = nacl.encoding.Base64Encoder
|
|
|
|
else:
|
|
|
|
encoding = nacl.encoding.RawEncoder
|
|
|
|
|
|
|
|
encrypted = box.encrypt(data, encoder=encoding)
|
|
|
|
return encrypted
|
|
|
|
|
|
|
|
def symmetricDecrypt(self, data, key, encodedKey=False, encodedMessage=False, returnEncoded=False):
|
|
|
|
'''Decrypt data to a 32-byte key (Salsa20-Poly1305 MAC)'''
|
|
|
|
if encodedKey:
|
|
|
|
encoding = nacl.encoding.Base64Encoder
|
|
|
|
else:
|
|
|
|
encoding = nacl.encoding.RawEncoder
|
|
|
|
box = nacl.secret.SecretBox(key, encoder=encoding)
|
|
|
|
|
|
|
|
if encodedMessage:
|
|
|
|
encoding = nacl.encoding.Base64Encoder
|
|
|
|
else:
|
|
|
|
encoding = nacl.encoding.RawEncoder
|
|
|
|
decrypted = box.decrypt(data, encoder=encoding)
|
|
|
|
if returnEncoded:
|
|
|
|
decrypted = base64.b64encode(decrypted)
|
|
|
|
return decrypted
|
2018-05-13 03:45:32 +00:00
|
|
|
|
2018-04-02 00:33:09 +00:00
|
|
|
def generateSymmetricPeer(self, peer):
|
|
|
|
'''Generate symmetric key for a peer and save it to the peer database'''
|
|
|
|
key = self.generateSymmetric()
|
|
|
|
self._core.setPeerInfo(peer, 'forwardKey', key)
|
2018-02-08 22:58:39 +00:00
|
|
|
return
|
2018-02-16 04:31:30 +00:00
|
|
|
|
2018-04-02 00:33:09 +00:00
|
|
|
def generateSymmetric(self):
|
|
|
|
'''Generate a symmetric key (bytes) and return it'''
|
|
|
|
return binascii.hexlify(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE))
|
|
|
|
|
2018-02-21 02:44:56 +00:00
|
|
|
def generatePubKey(self):
|
2018-04-23 02:58:24 +00:00
|
|
|
'''Generate a Ed25519 public key pair, return tuple of base32encoded pubkey, privkey'''
|
2018-02-21 02:44:56 +00:00
|
|
|
private_key = nacl.signing.SigningKey.generate()
|
|
|
|
public_key = private_key.verify_key.encode(encoder=nacl.encoding.Base32Encoder())
|
2018-04-25 04:04:12 +00:00
|
|
|
return (public_key.decode(), private_key.encode(encoder=nacl.encoding.Base32Encoder()).decode())
|
2018-05-13 03:45:32 +00:00
|
|
|
|
2018-04-25 06:56:40 +00:00
|
|
|
def pubKeyHashID(self, pubkey=''):
|
2018-04-25 04:04:12 +00:00
|
|
|
'''Accept a ed25519 public key, return a truncated result of X many sha3_256 hash rounds'''
|
2018-04-25 06:56:40 +00:00
|
|
|
if pubkey == '':
|
|
|
|
pubkey = self.pubKey
|
2018-04-25 04:04:12 +00:00
|
|
|
prev = ''
|
|
|
|
pubkey = pubkey.encode()
|
|
|
|
for i in range(self.HASH_ID_ROUNDS):
|
2018-04-26 20:39:02 +00:00
|
|
|
try:
|
|
|
|
prev = prev.encode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2018-04-25 04:04:12 +00:00
|
|
|
hasher = hashlib.sha3_256()
|
2018-04-26 20:39:02 +00:00
|
|
|
hasher.update(pubkey + prev)
|
2018-04-25 04:04:12 +00:00
|
|
|
prev = hasher.hexdigest()
|
|
|
|
result = prev
|
2018-05-05 21:50:15 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
def sha3Hash(self, data):
|
|
|
|
hasher = hashlib.sha3_256()
|
|
|
|
hasher.update(data)
|
|
|
|
return hasher.hexdigest()
|
2018-05-13 03:45:32 +00:00
|
|
|
|
2018-05-05 21:50:15 +00:00
|
|
|
def blake2bHash(self, data):
|
2018-05-05 23:32:10 +00:00
|
|
|
try:
|
|
|
|
data = data.encode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2018-05-13 03:45:32 +00:00
|
|
|
return nacl.hash.blake2b(data)
|
|
|
|
|
2018-07-08 07:51:23 +00:00
|
|
|
def verifyPow(self, blockContent):
|
2018-05-13 03:45:32 +00:00
|
|
|
'''
|
|
|
|
Verifies the proof of work associated with a block
|
|
|
|
'''
|
|
|
|
retData = False
|
|
|
|
|
|
|
|
dataLen = len(blockContent)
|
|
|
|
|
|
|
|
try:
|
2018-07-08 07:51:23 +00:00
|
|
|
blockContent = blockContent.encode()
|
2018-05-13 03:45:32 +00:00
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
2018-07-08 07:51:23 +00:00
|
|
|
blockHash = self.sha3Hash(blockContent)
|
2018-07-10 07:20:32 +00:00
|
|
|
try:
|
|
|
|
blockHash = blockHash.decode() # bytes on some versions for some reason
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2018-07-08 07:51:23 +00:00
|
|
|
|
2018-06-16 20:54:56 +00:00
|
|
|
difficulty = math.floor(dataLen / 1000000)
|
2018-05-13 03:45:32 +00:00
|
|
|
|
2018-06-16 20:54:56 +00:00
|
|
|
mainHash = '0000000000000000000000000000000000000000000000000000000000000000'#nacl.hash.blake2b(nacl.utils.random()).decode()
|
|
|
|
puzzle = mainHash[:difficulty]
|
|
|
|
|
2018-07-08 07:51:23 +00:00
|
|
|
if blockHash[:difficulty] == puzzle:
|
2018-06-16 20:54:56 +00:00
|
|
|
# logger.debug('Validated block pow')
|
|
|
|
retData = True
|
2018-05-13 03:45:32 +00:00
|
|
|
else:
|
2018-06-16 20:54:56 +00:00
|
|
|
logger.debug("Invalid token, bad proof")
|
2018-05-13 03:45:32 +00:00
|
|
|
|
|
|
|
return retData
|