15. API Reference

15.1. krypton.basic

Basic security related classes.

class krypton.basic.Crypto(keyDB: ~sqlalchemy.orm.session.Session = <sqlalchemy.orm.scoping.scoped_session object>)

Crypto Class (see Documentation)

secureCreate(data: ByteString, pwd: ByteString = None, _num: int = None)

Store Encrypted Data

Arguments:

data – Plaintext data

Keyword Arguments:

pwd – Password To Decrypt (default: {None})

_num – Unless you know what this is, not good idea to set! Id to store in DB (default: {None})

Returns:

Integer to be passed to secureRead to return data

secureDelete(num: int, pwd: ByteString = None) None

Delete Data set by secureCreate

Arguments:

num – Integer id of entry

Keyword Arguments:

pwd – Password (default: {None})

secureRead(num: int, pwd: ByteString)

Read data from secureCreate

Arguments:

num – Integer returned from secureCreate

pwd – Password set in secureCreate

Returns:

Plaintext data

secureUpdate(num: int, new: ByteString, pwd: ByteString)

Update Entry Set by secureCreate

Arguments:

num – Integer id of entry

new – New data to set

pwd – Password

class krypton.basic.KMS(keyDB: ~sqlalchemy.orm.session.Session = <sqlalchemy.orm.scoping.scoped_session object>)

They Key Management System

createNewKey(name: str, pwd: ByteString = None) str

Create a new key and store it

Arguments:

name – Name of the Key

Keyword Arguments:

pwd – Password (default: {None})

Raises:

KeyError: If key with same name already exists

Returns:

The key as python bytes

getKey(name: str, pwd: ByteString = None, force: bool = False) bytes

Get a Key

Arguments:

name – Name of the key to get

Keyword Arguments:

pwd – Password (default: {None})

force – Override Cryptoperiod Compliance errors (default: {False})

Raises:

ValueError: If the key does not exist

KeyManagementError: If the key has expired - set force=True to override

ValueError: If an unsupported cipher is used

ValueError: Wrong passwords were provided or the key was tampered with

Returns:

The key as python bytes

removeKey(name: str, pwd: ByteString = None) None

Delete a Key

Arguments:

name – Name of the Key

Keyword Arguments:

pwd – Password (default: {None})

exception krypton.basic.KeyManagementError(*args: object)

Error in Key Management System

For example, compliance issues

Arguments:

Exception – Inherits base Exception class

15.2. krypton.auth.users.bases

Contains Abstract Base Classes for user models. You can check this to see the declarations for functions.

exception krypton.auth.users.bases.UserError(*args: object)

Exception to be raised when an error occurs in a user model.

class krypton.auth.users.bases.user

Base Class for User Models. You can check this to see whether a method is implemented in user models.

abstract decryptWithUserKey(data: ByteString, salt: bytes = None, sender=None) bytes

Decrypt data with user’s key

Arguments:

data – Ciphertext

salt – Salt

Keyword Arguments:

sender – If applicable sender’s user name (default: {None})

Returns:

Plaintext

abstract delete()

Delete a user

Returns:

None

abstract deleteData(name: str) None

Delete key-value pair set by setData

Arguments:

name – The key to remove

abstract disableMFA()

The method name says it all.

abstract enableMFA()

The method name says it all.

abstract enablePWDReset()

Enable Password Reset

Arguments:

key – The key needed to reset

abstract encryptWithUserKey(data: ByteString, otherUsers: list[str]) bytes

Encrypt data with user’s key

Arguments:

data – Plaintext

Keyword Arguments:

otherUsers – List of user nameswho can decrypt it (default: {None})

Returns:

List of tuples of form (user name, ciphertext, salt), check: https://docs.krptn.dev/README-USER-AUTH.html#encryption.

abstract generateNewKeys(pwd: str)

Regenerate Encryption keys

Arguments:

pwd – Password

abstract getData(name: str) ByteString

Get value set by setData

Arguments:

name – the key

Raises:

AttributeError: if a value is not set

Returns:

The value

abstract getLogs() list[list[datetime.datetime, bool]]

getLogs Get the login logs for the user

abstract logFailure()

logFailure Log a login failure

abstract login(pwd: str, mfaToken: str = None, fido: str = None)

Log the user in

Keyword Arguments:

pwd – Password (default: {None})

otp – One-Time Password (default: {None})

fido – Fido Token (default: {None})

Raises:

UserError: Password is not set

Returns:

Session Key, None if user is not saved

abstract logout()

logout Logout the user and delete the current Session

abstract reload()

Reload encryption keys. Warning: previous keys are not purged!

abstract resetPWD(key: str, newPWD: str)

Reset Password

Arguments:

key – Key as provided to enablePWDReset

abstract restoreSession(key: bytes)

Resume session from key

Arguments:

key – Session Key

abstract revokeSessions()

Revoke all Sessions for this User

Raises:

UserError: If the user does not exist

abstract saveNewUser(name: str, pwd: str)

Save a new user

Arguments:

name – User Name

pwd – Password

Keyword Arguments:

fido – Fido Token (default: {None})

Raises:

ValueError: If user is already saved

abstract setData(name: str, value: any) None

Store user data as a key-value pair

Arguments:

name – key

value – value

abstract shareDelete(name: str) None

shareDelete Delete data set by shareSet

Arguments:

name – Name of the data

abstract shareGet(name: str) bytes

Get data set by shareSet

Arguments:

name – The “name of the data”

Raises:

ValueError: if decryption fails

Returns:

Decrypted data

abstract shareSet(name: str, data: ByteString, otherUsers: list[str]) None

Set data readable by others

Arguments:

name – The “name” of the data

data – The data

otherUsers – List of usernames who should read it

krypton.auth.users.bases.userExistRequired(func)

User has to be saved in order to run this function

Arguments:

func – function

Raises:

UserError: If user is not saved

Returns:

inner1

15.3. krypton.auth.users.userModel

Provides User Models Note for developer’s working on Krypton: this only contains user model cryptography.

class krypton.auth.users.userModel.standardUser(userName: str = None, userID: int = None)

User Model for Krypton Check documentation.

decryptWithUserKey(data: ByteString, sender=None) bytes

Decrypt data with user’s key

Arguments:

data – Ciphertext

Keyword Arguments:

sender – If applicable sender’s user name (default: {None})

Raises:

ValueError: if decryption fails

Returns:

Plaintext

deleteData(name: str) None

Delete key-value pair set by setData

Arguments:

name – The key to remove

encryptWithUserKey(data: ByteString, otherUsers: list[int] = None) list[tuple[str, bytes, bytes]]

Encrypt data with user’s key

Arguments:

data – Plaintext

Keyword Arguments:

otherUsers – List of user names who can decrypt it (default: {None})

Returns:

If otherUsers is None: ciphertext.

If otherUsers is not None: list of tuples (check https://docs.krptn.dev/README-USER-AUTH.html#encryption).

generateNewKeys(pwd: str)

Regenerate Encryption keys

Arguments:

pwd – Password

getData(name: str) ByteString

Get value set by setData

Arguments:

name – the key

Raises:

ValueError: if decryption fails, or if a value is not set

Returns:

The value

reload()

Reload encryption keys. Warning: previous keys are not purged!

setData(name: str, value: any) None

Store user data as a key-value pair

Arguments:

name – key

value – value

shareDelete(name: str) None

shareDelete Delete data set by shareSet

Arguments:

name – Name of the data

shareGet(name: str) bytes

Get data set by shareSet

Arguments:

name – The “name of the data”

Raises:

ValueError: if decryption fails or requested data does not exist

Returns:

Decrypted data

shareSet(name: str, data: ByteString, otherUsers: list[str]) None

Set data readable by others

Arguments:

name – The “name” of the data

data – The data

otherUsers – List of usernames who should read it

15.4. krypton.auth.users.userModelBaseAuth

This module contains auth functions for models

class krypton.auth.users.userModelBaseAuth.AuthUser

Auth Logic for User Models

changeUserName(newUserName: str)

changeUserName Change the user’s username

Arguments:

newUserName – The new username (string)

delete()

Delete a user

getLogs()

getLogs Get the login logs for the user

logFailure()

logFailure Log a login failure

login(pwd: str, mfaToken: str = '', fido: str = None)

Log the user in

Keyword Arguments:

pwd – Password

otp – One-Time Password (default: {“”})

fido – Fido Credentials (default: {None})

Raises:

UserError: Password is not set or wrong password is provided.

Returns:

Session Key

logout()

logout Logout the user and delete the current Session

restoreSession(key)

Resume sessoin from key

Arguments:

key – Session Key

revokeSessions()

Revoke all Sessions for this User

Raises:

UserError: If the user does not exist

saveNewUser(name: str, pwd: str) bytes

Save a new user

Arguments:

name – User Name

pwd – Password

Raises:

ValueError: If user is already saved

15.5. krypton.auth.users.userModelMFAAuth

Extended auth logic

class krypton.auth.users.userModelMFAAuth.MFAUser

MFA for Krypton Users

beginFIDOSetup()

Being FIDO Registration

completeFIDOSetup(response)

Finish FIDO Setup

Arguments:

repsonse – The response from the client

disableMFA()

Disable TOTP based MFA

disablePWDReset()

Disbale PWD and revoke all codes

enableMFA()

Enable TOTP MFA

Returns:

base32 encoded shared secret, QR code string

enablePWDReset() list[str]

Enable PWD Reset

Returns:

The recovery codes that unlock the account

getFIDOOptions()

Obtain FIDO options before Auth

Returns:

Fido Options as string, { “error”: “No keys availble” } if FIDO is not setup

removeFIDO()

Remove the FIDO Auth from Server

resetPWD(key: str, newPWD: str)

Reset Password

Arguments:

key – Key as provided to enablePWDReset

15.6. krypton.auth.factors

Different Auth Factors available inside krypton.

exception krypton.auth.factors.AuthFailed(*args: object)

Exception to be raised when an error occures in a user model.

class krypton.auth.factors.fido

FIDO authentication support.

static authenticate(cred_id)

Begin user authentication

Arguments:

cred_id – The user’s credential’s id

Returns:

verification options, expected challange

static authenticate_verify(challenge: bytes, credential_public_key, credentials)

Complete Authentication

Arguments:

challenge – The expected challange from authenticate

credential_public_key – The user’s public key

credentials – The credentials provided by the user

Returns:

True on success, False otherwise

static register(userID: int, userName: str)

Start FIDO auth registration process

Arguments:

userID – User’s ID

userName – The User’s username

Returns:

registration options and registration challenge

static register_verification(credentials, challenge)

Complete registration

Arguments:

credentials – The user’s fido credentials, recieved from the browser

challenge – The expected challenge

Raises:

AuthError: registration failure

Returns:

credential id and credential public key

class krypton.auth.factors.password

Note: no need to create an object just call the methods directly. Simple password authentication.

1.) Hash the password with PBKDF2 and random salt.

2.) Decrypt the value in the table arg.

3.) Verify that the decryption was successfully authenticated.

4.) Return the encryption key.

static auth(authTag: str, pwd: str) bytes

Authenticate against a tag

Arguments:

authTag – Tag

pwd – Password

Returns:

Encryption key if success, False otherwise

static getAuth(pwd: str)

Generate authentication tag for later use

Arguments:

pwd – Password

Returns:

Auth tag

class krypton.auth.factors.totp

Simple TOTP authentication

static createTOTP(userName: str)

Create parameters for TOTP Generate

Arguments:

userName – The username

Returns:

shared secret, base32 encoded shared secret, totp uri

static verifyTOTP(secret: bytes, otp: str) bool

Verify TOTP

Arguments:

secret – The Shared secret

otp – The OTP

Returns:

True if success False otherwise

15.7. krypton.auth._utils

Utils to help code

krypton.auth._utils.cleanUpSessions(session: scoped_session, userID: int = None)

Cleanup Expired Session or Remove all sessions for a user

Arguments:

session – The database session to use

Keyword Arguments:

userID – The ID for which to delete all sessions (even if not expired) (default: {None})

15.8. krypton.base

Loads __CryptoLib and contains wrappers.

krypton.base.base64decode(data: ByteString) ByteString

Decode base64

Arguments:

data – Base64 encoded string

Returns:

Base64 decoded bytes

krypton.base.base64encode(data: ByteString) str

Base64 Encoding

Arguments:

data – Text to encode

Returns:

Base64 encoded string

krypton.base.createECCKey() tuple[str, str]

create an Eliptic Curve Key

Encoded in P.E.M. format

Returns:

Returns a tuple like (privateKey:str, publicKey:str)

krypton.base.createTOTPString(secret: bytes, user: str) str

Create a TOTP String that can be scanned by Auth Apps

Arguments:

secret – The shared secret

Returns:

The String to be converted to QR code

krypton.base.decryptEcc(privKey: bytes, pubKey: bytes, data: ByteString) bytes

Decrypt data using public/private keys

Args:

privKey (bytes): Private Key pubKey (bytes): Public Key data (ByteString): Data to decrypt

Returns:

bytes: the decrypted data

krypton.base.encryptEcc(privKey: bytes, pubKey: bytes, data: ByteString) bytes

Encrypt data using public/private keys

Args:

privKey (bytes): Private Key pubKey (bytes): Public Key data (ByteString): Data to encrypt

Returns:

bytes: the encrypted data

krypton.base.genOTP() str

Generate an 12-digit OTP/PIN.

Returns:

The OTP/PIN as python string

krypton.base.passwordHash(text: ByteString, salt: ByteString, opsLimit: int = 3, keylen: int = 32) bytes

Argon2id

Arguments:

text – Plain text salt – Salt

Keyword Arguments:

keylen – Len of key to return (default: {32}) opsLimit – Ops Limit for Argon2id

Returns:

The key as python bytes

krypton.base.seal(data: ByteString, key: bytes) bytes

Encrypt Data for at rest storage

Arguments:

data – Plain text

key – 32-byte key

Returns:

Cipher text

krypton.base.sleepOutOfGIL(seconds: int = 5) bool

Sleep for seconds while releasing the GIL.

Keyword Arguments:

seconds – Number of seconds to sleep for (default: {5})

Returns:

True

krypton.base.unSeal(data: bytes, key: bytes) bytes

Decrypt Data from restEncrypt

Arguments:

data – Cipher text

key – 32-byte key

Returns:

Plain text

krypton.base.verifyTOTP(secret: bytes, code: str) bool

Verify a 6-digit TOTP

Arguments:

secret – The shared secret

code – The code to verify

Returns:

True is success False otherwise

krypton.base.zeromem(obj: ByteString) int

Set the byte/string to x00

WARNING! Improper use leads to severe memory corruption. Ensure you only use it with bytes and string objects. Also, on PyPy this function does nothing to avoid corruption.

Arguments:

obj – Object to do this on (bytes and str are supported!)

Returns:

Result from memset.