Search code examples
opensslrsa

How to generate a weak (e.g. 128-bit) RSA key?


I would like to do some testing with very weak RSA keys, like 128-bit or 256-bit to practice a little bit. But OpenSSL denies the creation of such weak keys with

$ openssl genrsa -out test.key 128
Error setting RSA length
40C7C155167F0000:error:1C8000AB:Provider routines:rsa_gen_set_params:key size too small:../providers/implementations/keymgmt/rsa_kmgmt.c:514:

I'm completely aware that such a key is about as secure as no encryption at all, because it can be factored in milliseconds, which is the whole point of the thing.

Aside from manually piecing together a weak key in a hex editor, how would you do such a thing?


Solution

  • Newer versions of OpenSSL do not support genrsa numbits below 512.

    The default is 2048 and values less than 512 are not allowed.

    I had no issue using openssl genrsa -out rsa.key 128 with LibreSSL 3.3.6

    Here's some Python code that will generate keys; modify it as needed.

    WARNING: These keys should never be used for anything.

    import rsa
    
    pubkey,privkey = rsa.newkeys(128)
    print(pubkey.save_pkcs1('PEM').decode('UTF-8'))
    print(privkey.save_pkcs1('PEM').decode('UTF-8'))
    
    pubkey,privkey = rsa.newkeys(256)
    print(pubkey.save_pkcs1('PEM').decode('UTF-8'))
    print(privkey.save_pkcs1('PEM').decode('UTF-8'))
    

    Output:

    -----BEGIN RSA PUBLIC KEY----- MBgCEQCl/IGtHk0lD0CvdwOKbFtzAgMBAAE=
    -----END RSA PUBLIC KEY-----

    -----BEGIN RSA PRIVATE KEY----- MGICAQACEQCl/IGtHk0lD0CvdwOKbFtzAgMBAAECEHp0P8LU8PrWWHEKUcKIQxEC CQv3mIVsiuS4yQIIDd7BlSarTFsCCQtwCEE1XYZ/KQIIBs84/O/aI4cCCQazNJyo Sa762g==
    -----END RSA PRIVATE KEY-----

    -----BEGIN RSA PUBLIC KEY----- MCgCIQC0uFXIkpfJTJNMCsc4UTHvkfUGgs1dW3r9OLEBSnNCVwIDAQAB
    -----END RSA PUBLIC KEY-----

    -----BEGIN RSA PRIVATE KEY----- MIGsAgEAAiEAtLhVyJKXyUyTTArHOFEx75H1BoLNXVt6/TixAUpzQlcCAwEAAQIh AJ9X/UNJhg4Wt7WPt1K/u/mPU9MwrXCqQVIPCXLrwuoRAhIA9DxAuEES2PbGPi5k 0hdwvk8CEAC9bNqhV9lSmjAn7XwlAXkCEgC7HsqrIFgzWGYsT9k4yXK8qwIPRsU1 hZQRsKfEmBZFDHpZAhEv3CG7tGSFobuQzMFxO4643A==
    -----END RSA PRIVATE KEY-----

    References
    OpenSSL genrsa
    Python RSA