renamed onionr dir and bugfixes/linting progress
This commit is contained in:
parent
2b996da17f
commit
720efe4fca
226 changed files with 179 additions and 142 deletions
27
src/onionrcrypto/__init__.py
Executable file
27
src/onionrcrypto/__init__.py
Executable file
|
@ -0,0 +1,27 @@
|
|||
'''
|
||||
Onionr - Private P2P Communication
|
||||
|
||||
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/>.
|
||||
'''
|
||||
|
||||
from . import generate, hashers, getourkeypair, signing, encryption, cryptoutils
|
||||
generate_deterministic = generate.generate_deterministic
|
||||
generate = generate.generate_pub_key
|
||||
|
||||
keypair = getourkeypair.get_keypair()
|
||||
pub_key = keypair[0]
|
||||
priv_key = keypair[1]
|
8
src/onionrcrypto/cryptoutils/__init__.py
Normal file
8
src/onionrcrypto/cryptoutils/__init__.py
Normal file
|
@ -0,0 +1,8 @@
|
|||
from . import safecompare, replayvalidation, randomshuffle, verifypow
|
||||
from . import getpubfrompriv
|
||||
|
||||
replay_validator = replayvalidation.replay_timestamp_validation
|
||||
random_shuffle = randomshuffle.random_shuffle
|
||||
safe_compare = safecompare.safe_compare
|
||||
verify_POW = verifypow.verify_POW
|
||||
get_pub_key_from_priv = getpubfrompriv.get_pub_key_from_priv
|
6
src/onionrcrypto/cryptoutils/getpubfrompriv.py
Normal file
6
src/onionrcrypto/cryptoutils/getpubfrompriv.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
from nacl import signing, encoding
|
||||
|
||||
from onionrtypes import UserID, UserIDSecretKey
|
||||
|
||||
def get_pub_key_from_priv(priv_key: UserIDSecretKey, raw_encoding:bool=False)->UserID:
|
||||
return signing.SigningKey(priv_key, encoder=encoding.Base32Encoder).verify_key.encode(encoding.Base32Encoder)
|
13
src/onionrcrypto/cryptoutils/randomshuffle.py
Normal file
13
src/onionrcrypto/cryptoutils/randomshuffle.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
import secrets
|
||||
def random_shuffle(theList):
|
||||
myList = list(theList)
|
||||
shuffledList = []
|
||||
myListLength = len(myList) + 1
|
||||
while myListLength > 0:
|
||||
removed = secrets.randbelow(myListLength)
|
||||
try:
|
||||
shuffledList.append(myList.pop(removed))
|
||||
except IndexError:
|
||||
pass
|
||||
myListLength = len(myList)
|
||||
return shuffledList
|
6
src/onionrcrypto/cryptoutils/replayvalidation.py
Normal file
6
src/onionrcrypto/cryptoutils/replayvalidation.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
from onionrutils import epoch
|
||||
def replay_timestamp_validation(timestamp):
|
||||
if epoch.get_epoch() - int(timestamp) > 2419200:
|
||||
return False
|
||||
else:
|
||||
return True
|
12
src/onionrcrypto/cryptoutils/safecompare.py
Normal file
12
src/onionrcrypto/cryptoutils/safecompare.py
Normal file
|
@ -0,0 +1,12 @@
|
|||
import hmac
|
||||
def safe_compare(one, two):
|
||||
# Do encode here to avoid spawning core
|
||||
try:
|
||||
one = one.encode()
|
||||
except AttributeError:
|
||||
pass
|
||||
try:
|
||||
two = two.encode()
|
||||
except AttributeError:
|
||||
pass
|
||||
return hmac.compare_digest(one, two)
|
38
src/onionrcrypto/cryptoutils/verifypow.py
Normal file
38
src/onionrcrypto/cryptoutils/verifypow.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
from .. import hashers
|
||||
import config, onionrproofs, logger
|
||||
import onionrexceptions
|
||||
def verify_POW(blockContent):
|
||||
'''
|
||||
Verifies the proof of work associated with a block
|
||||
'''
|
||||
retData = False
|
||||
|
||||
dataLen = len(blockContent)
|
||||
|
||||
try:
|
||||
blockContent = blockContent.encode()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
blockHash = hashers.sha3_hash(blockContent)
|
||||
try:
|
||||
blockHash = blockHash.decode() # bytes on some versions for some reason
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
difficulty = onionrproofs.getDifficultyForNewBlock(blockContent)
|
||||
|
||||
if difficulty < int(config.get('general.minimum_block_pow')):
|
||||
difficulty = int(config.get('general.minimum_block_pow'))
|
||||
mainHash = '0000000000000000000000000000000000000000000000000000000000000000'#nacl.hash.blake2b(nacl.utils.random()).decode()
|
||||
puzzle = mainHash[:difficulty]
|
||||
|
||||
if blockHash[:difficulty] == puzzle:
|
||||
# logger.debug('Validated block pow')
|
||||
retData = True
|
||||
else:
|
||||
logger.debug("Invalid token, bad proof")
|
||||
raise onionrexceptions.InvalidProof('Proof for %s needs to be %s' % (blockHash, puzzle))
|
||||
|
||||
return retData
|
||||
|
47
src/onionrcrypto/encryption/__init__.py
Normal file
47
src/onionrcrypto/encryption/__init__.py
Normal file
|
@ -0,0 +1,47 @@
|
|||
import nacl.encoding, nacl.public, nacl.signing
|
||||
from .. import getourkeypair
|
||||
import unpaddedbase32
|
||||
from onionrutils import bytesconverter, stringvalidators
|
||||
pair = getourkeypair.get_keypair()
|
||||
our_pub_key = unpaddedbase32.repad(pair[0].encode())
|
||||
our_priv_key = unpaddedbase32.repad(pair[1].encode())
|
||||
|
||||
def pub_key_encrypt(data, pubkey, encodedData=False):
|
||||
'''Encrypt to a public key (Curve25519, taken from base32 Ed25519 pubkey)'''
|
||||
pubkey = unpaddedbase32.repad(bytesconverter.str_to_bytes(pubkey))
|
||||
retVal = ''
|
||||
box = None
|
||||
data = bytesconverter.str_to_bytes(data)
|
||||
|
||||
pubkey = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.Base32Encoder()).to_curve25519_public_key()
|
||||
|
||||
if encodedData:
|
||||
encoding = nacl.encoding.Base64Encoder
|
||||
else:
|
||||
encoding = nacl.encoding.RawEncoder
|
||||
|
||||
box = nacl.public.SealedBox(pubkey)
|
||||
retVal = box.encrypt(data, encoder=encoding)
|
||||
|
||||
return retVal
|
||||
|
||||
def pub_key_decrypt(data, pubkey='', privkey='', encodedData=False):
|
||||
'''pubkey decrypt (Curve25519, taken from Ed25519 pubkey)'''
|
||||
if pubkey != '':
|
||||
pubkey = unpaddedbase32.repad(bytesconverter.str_to_bytes(pubkey))
|
||||
decrypted = False
|
||||
if encodedData:
|
||||
encoding = nacl.encoding.Base64Encoder
|
||||
else:
|
||||
encoding = nacl.encoding.RawEncoder
|
||||
if privkey == '':
|
||||
privkey = our_priv_key
|
||||
ownKey = nacl.signing.SigningKey(seed=privkey, encoder=nacl.encoding.Base32Encoder()).to_curve25519_private_key()
|
||||
|
||||
if stringvalidators.validate_pub_key(privkey):
|
||||
privkey = nacl.signing.SigningKey(seed=privkey, encoder=nacl.encoding.Base32Encoder()).to_curve25519_private_key()
|
||||
anonBox = nacl.public.SealedBox(privkey)
|
||||
else:
|
||||
anonBox = nacl.public.SealedBox(ownKey)
|
||||
decrypted = anonBox.decrypt(data, encoder=encoding)
|
||||
return decrypted
|
27
src/onionrcrypto/generate.py
Normal file
27
src/onionrcrypto/generate.py
Normal file
|
@ -0,0 +1,27 @@
|
|||
import nacl.signing, nacl.encoding, nacl.pwhash
|
||||
import onionrexceptions
|
||||
from onionrutils import bytesconverter
|
||||
from etc import onionrvalues
|
||||
def generate_pub_key():
|
||||
'''Generate a Ed25519 public key pair, return tuple of base32encoded pubkey, privkey'''
|
||||
private_key = nacl.signing.SigningKey.generate()
|
||||
public_key = private_key.verify_key.encode(encoder=nacl.encoding.Base32Encoder())
|
||||
return (public_key.decode(), private_key.encode(encoder=nacl.encoding.Base32Encoder()).decode())
|
||||
|
||||
def generate_deterministic(passphrase, bypassCheck=False):
|
||||
'''Generate a Ed25519 public key pair from a password'''
|
||||
passStrength = onionrvalues.PASSWORD_LENGTH
|
||||
passphrase = bytesconverter.str_to_bytes(passphrase) # Convert to bytes if not already
|
||||
# Validate passphrase length
|
||||
if not bypassCheck:
|
||||
if len(passphrase) < passStrength:
|
||||
raise onionrexceptions.PasswordStrengthError("Passphase must be at least %s characters" % (passStrength,))
|
||||
# KDF values
|
||||
kdf = nacl.pwhash.argon2id.kdf
|
||||
salt = b"U81Q7llrQcdTP0Ux" # Does not need to be unique or secret, but must be 16 bytes
|
||||
ops = nacl.pwhash.argon2id.OPSLIMIT_SENSITIVE
|
||||
mem = nacl.pwhash.argon2id.MEMLIMIT_SENSITIVE
|
||||
|
||||
key = kdf(32, passphrase, salt, opslimit=ops, memlimit=mem) # Generate seed for ed25519 key
|
||||
key = nacl.signing.SigningKey(key)
|
||||
return (key.verify_key.encode(nacl.encoding.Base32Encoder).decode(), key.encode(nacl.encoding.Base32Encoder).decode())
|
36
src/onionrcrypto/getourkeypair.py
Normal file
36
src/onionrcrypto/getourkeypair.py
Normal file
|
@ -0,0 +1,36 @@
|
|||
"""
|
||||
Onionr - Private P2P Communication
|
||||
|
||||
returns our current active keypair
|
||||
"""
|
||||
"""
|
||||
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/>.
|
||||
"""
|
||||
import os
|
||||
import keymanager, config, filepaths
|
||||
from . import generate
|
||||
def get_keypair():
|
||||
key_m = keymanager.KeyManager()
|
||||
if os.path.exists(filepaths.keys_file):
|
||||
if len(config.get('general.public_key', '')) > 0:
|
||||
pubKey = config.get('general.public_key')
|
||||
else:
|
||||
pubKey = key_m.getPubkeyList()[0]
|
||||
privKey = key_m.getPrivkey(pubKey)
|
||||
else:
|
||||
keys = generate.generate_pub_key()
|
||||
pubKey = keys[0]
|
||||
privKey = keys[1]
|
||||
key_m.addKey(pubKey, privKey)
|
||||
return (pubKey, privKey)
|
16
src/onionrcrypto/hashers.py
Normal file
16
src/onionrcrypto/hashers.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
import hashlib, nacl.hash
|
||||
def sha3_hash(data):
|
||||
try:
|
||||
data = data.encode()
|
||||
except AttributeError:
|
||||
pass
|
||||
hasher = hashlib.sha3_256()
|
||||
hasher.update(data)
|
||||
return hasher.hexdigest()
|
||||
|
||||
def blake2b_hash(data):
|
||||
try:
|
||||
data = data.encode()
|
||||
except AttributeError:
|
||||
pass
|
||||
return nacl.hash.blake2b(data)
|
45
src/onionrcrypto/signing/__init__.py
Normal file
45
src/onionrcrypto/signing/__init__.py
Normal file
|
@ -0,0 +1,45 @@
|
|||
import base64, binascii
|
||||
|
||||
import unpaddedbase32
|
||||
import nacl.encoding, nacl.signing, nacl.exceptions
|
||||
|
||||
from onionrutils import bytesconverter
|
||||
from onionrutils import mnemonickeys
|
||||
import logger
|
||||
|
||||
def ed_sign(data, key, encodeResult=False):
|
||||
'''Ed25519 sign data'''
|
||||
key = unpaddedbase32.repad(bytesconverter.str_to_bytes(key))
|
||||
try:
|
||||
data = data.encode()
|
||||
except AttributeError:
|
||||
pass
|
||||
key = nacl.signing.SigningKey(seed=key, encoder=nacl.encoding.Base32Encoder)
|
||||
retData = ''
|
||||
if encodeResult:
|
||||
retData = key.sign(data, encoder=nacl.encoding.Base64Encoder).signature.decode() # .encode() is not the same as nacl.encoding
|
||||
else:
|
||||
retData = key.sign(data).signature
|
||||
return retData
|
||||
|
||||
def ed_verify(data, key, sig, encodedData=True):
|
||||
'''Verify signed data (combined in nacl) to an ed25519 key'''
|
||||
key = unpaddedbase32.repad(bytesconverter.str_to_bytes(key))
|
||||
try:
|
||||
key = nacl.signing.VerifyKey(key=key, encoder=nacl.encoding.Base32Encoder)
|
||||
except nacl.exceptions.ValueError:
|
||||
return False
|
||||
except binascii.Error:
|
||||
logger.warn('Could not load key for verification, invalid padding')
|
||||
return False
|
||||
retData = False
|
||||
sig = base64.b64decode(sig)
|
||||
try:
|
||||
data = data.encode()
|
||||
except AttributeError:
|
||||
pass
|
||||
try:
|
||||
retData = key.verify(data, sig) # .encode() is not the same as nacl.encoding
|
||||
except nacl.exceptions.BadSignatureError:
|
||||
pass
|
||||
return retData
|
Loading…
Add table
Add a link
Reference in a new issue