Onionr/src/onionrcrypto/generate.py

66 lines
2.3 KiB
Python
Raw Normal View History

2020-09-19 21:01:31 +00:00
"""Onionr - Private P2P Communication.
functions to generate ed25519 key pairs
"""
import nacl.signing
import nacl.encoding
import nacl.pwhash
2019-07-25 16:14:13 +00:00
import onionrexceptions
from onionrutils import bytesconverter
2019-07-27 20:29:15 +00:00
from etc import onionrvalues
2020-09-19 21:01:31 +00:00
"""
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/>.
"""
2019-07-19 19:49:56 +00:00
def generate_pub_key():
2020-09-19 21:01:31 +00:00
"""Generate a Ed25519 public key pair.
return tuple of base32encoded pubkey, privkey
"""
2019-07-19 19:49:56 +00:00
private_key = nacl.signing.SigningKey.generate()
2020-09-19 21:01:31 +00:00
public_key = private_key.verify_key.encode(
encoder=nacl.encoding.Base32Encoder())
return (public_key.decode(), private_key.encode(
encoder=nacl.encoding.Base32Encoder()).decode())
2019-07-25 16:14:13 +00:00
def generate_deterministic(passphrase, bypassCheck=False):
2020-09-19 21:01:31 +00:00
"""Generate a Ed25519 public key pair from a phase.
not intended for human-generated key
"""
2019-07-27 20:29:15 +00:00
passStrength = onionrvalues.PASSWORD_LENGTH
2020-09-19 21:01:31 +00:00
# Convert to bytes if not already
passphrase = bytesconverter.str_to_bytes(passphrase)
2019-07-25 16:14:13 +00:00
# Validate passphrase length
if not bypassCheck:
if len(passphrase) < passStrength:
2020-09-19 21:01:31 +00:00
raise onionrexceptions.PasswordStrengthError(
"Passphase must be at least %s characters" % (passStrength,))
2019-07-25 16:14:13 +00:00
# KDF values
kdf = nacl.pwhash.argon2id.kdf
2020-09-19 21:01:31 +00:00
# Does not need to be secret, but must be 16 bytes
salt = b"U81Q7llrQcdTP0Ux"
2019-07-25 16:14:13 +00:00
ops = nacl.pwhash.argon2id.OPSLIMIT_SENSITIVE
mem = nacl.pwhash.argon2id.MEMLIMIT_SENSITIVE
2020-09-19 21:01:31 +00:00
# Generate seed for ed25519 key
key = kdf(32, passphrase, salt, opslimit=ops, memlimit=mem)
2019-07-25 16:14:13 +00:00
key = nacl.signing.SigningKey(key)
2020-09-19 21:01:31 +00:00
return (
key.verify_key.encode(nacl.encoding.Base32Encoder).decode(),
key.encode(nacl.encoding.Base32Encoder).decode())