mercredi 9 mars 2022

How to use 128 bits of key with stream cipher's salsa20

I am working on an encryption to create a stateful stream cipher with 128 bits. I am using a pseduo random function to create a one-128 bits of key to use with with the stream cipher.

from drbg import *


# Generate twice the amount of pseudorandom
# data as the byte size of the given seed
# break the output in two parts: left, right
def PRG(seed):
    assert isinstance(seed, bytes)
    drbg = DRBG(seed)
    rnd = drbg.generate(2 * len(seed))
    return rnd[:len(seed)], rnd[len(seed):]


def PRF(key, msg):
    # assert isinstance(key, bytes)
    # assert isinstance(msg, bytes)
    # convert data into sequence of bits
    msgBits = "".join(format(byte, '08b') for byte in msg)
    seed = key  # initialize the seed with the key
    for b in msgBits:
        rnd = PRG(seed)[int(b)]
        seed = rnd
    return rnd

new_random = PRF(b'\x00' * 5, b'\x00' * 5)
print(new_random) 
# b' A\xa8~\xb5<\xa3%L\xb3\r\x1a\x99>\xc6\x05\xe0\xed\x80F\xa8\xa4qZ\x0cu.o\xad\xf7\xce\xa3\x9b\x90\x87\xb7\x02\xf4\x9a\xa8\xbc\xf8v\xae\xd2 \x87x@\xf0\x19B\xfbM3\xd4lh\xdf\xc5\xc0|\x85\xde'

Then I use the 128 bits of key with the stateful stream cipher below:

from Crypto.Cipher import Salsa20
from prf import *

# encrypt (Salsa)
ptxt = b'STREAM CIPHERS'
print("Ptxt:", ptxt)
myKey = b'new_random'
cipher = Salsa20.new(key=myKey)
ctxt = cipher.nonce + cipher.encrypt(ptxt)  # concatenate
print("Ctxt:", ctxt.hex())

However, I ran into this error :

Traceback (most recent call last):
  File "----", line 8, in <module>
    cipher = Salsa20.new(key=myKey)
  File "------", line 160, in new
    return Salsa20Cipher(key, nonce)
  File "-----", line 60, in __init__
    raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key))
ValueError: Incorrect key length for Salsa20 (10 bytes)

I wonder if anyone has any advice or suggestion? Thanks




Aucun commentaire:

Enregistrer un commentaire