1.. _usage: 2 3Usage 4================================================== 5 6This section describes the usage of the Python-RSA module. 7 8Before you can use RSA you need keys. You will receive a private key 9and a public key. 10 11.. important:: 12 13 The private key is called *private* for a reason. Never share this 14 key with anyone. 15 16The public key is used for encypting a message such that it can only 17be read by the owner of the private key. As such it's also referred to 18as the *encryption key*. Decrypting a message can only be done using 19the private key, hence it's also called the *decryption key*. 20 21The private key is used for signing a message. With this signature and 22the public key, the receiver can verifying that a message was signed 23by the owner of the private key, and that the message was not modified 24after signing. 25 26Generating keys 27-------------------------------------------------- 28 29You can use the :py:func:`rsa.newkeys` function to create a keypair: 30 31 >>> (pubkey, privkey) = rsa.newkeys(512) 32 33Alternatively you can use :py:meth:`rsa.PrivateKey.load_pkcs1` and 34:py:meth:`rsa.PublicKey.load_pkcs1` to load keys from a file: 35 36 >>> with open('private.pem') as privatefile: 37 ... keydata = privatefile.read() 38 >>> pubkey = rsa.PrivateKey.load_pkcs1(keydata) 39 40 41Time to generate a key 42++++++++++++++++++++++++++++++++++++++++ 43 44Generating a keypair may take a long time, depending on the number of 45bits required. The number of bits determines the cryptographic 46strength of the key, as well as the size of the message you can 47encrypt. If you don't mind having a slightly smaller key than you 48requested, you can pass ``accurate=False`` to speed up the key 49generation process. 50 51Another way to speed up the key generation process is to use multiple 52processes in parallel to speed up the key generation. Use no more than 53the number of processes that your machine can run in parallel; a 54dual-core machine should use ``poolsize=2``; a quad-core 55hyperthreading machine can run two threads on each core, and thus can 56use ``poolsize=8``. 57 58 >>> (pubkey, privkey) = rsa.newkeys(512, poolsize=8) 59 60These are some average timings from my desktop machine (Linux 2.6, 612.93 GHz quad-core Intel Core i7, 16 GB RAM) using 64-bit CPython 2.7. 62Since key generation is a random process, times may differ even on 63similar hardware. On all tests, we used the default ``accurate=True``. 64 65+----------------+------------------+------------------+ 66| Keysize (bits) | single process | eight processes | 67+================+==================+==================+ 68| 128 | 0.01 sec. | 0.01 sec. | 69+----------------+------------------+------------------+ 70| 256 | 0.03 sec. | 0.02 sec. | 71+----------------+------------------+------------------+ 72| 384 | 0.09 sec. | 0.04 sec. | 73+----------------+------------------+------------------+ 74| 512 | 0.11 sec. | 0.07 sec. | 75+----------------+------------------+------------------+ 76| 1024 | 0.79 sec. | 0.30 sec. | 77+----------------+------------------+------------------+ 78| 2048 | 6.55 sec. | 1.60 sec. | 79+----------------+------------------+------------------+ 80| 3072 | 23.4 sec. | 7.14 sec. | 81+----------------+------------------+------------------+ 82| 4096 | 72.0 sec. | 24.4 sec. | 83+----------------+------------------+------------------+ 84 85If key generation is too slow for you, you could use OpenSSL to 86generate them for you, then load them in your Python code. OpenSSL 87generates a 4096-bit key in 3.5 seconds on the same machine as used 88above. See :ref:`openssl` for more information. 89 90Key size requirements 91-------------------------------------------------- 92 93Python-RSA version 3.0 introduced PKCS#1-style random padding. This 94means that 11 bytes (88 bits) of your key are no longer usable for 95encryption, so keys smaller than this are unusable. The larger the 96key, the higher the security. 97 98Creating signatures also requires a key of a certain size, depending 99on the used hash method: 100 101+-------------+-----------------------------------+ 102| Hash method | Suggested minimum key size (bits) | 103+=============+===================================+ 104| MD5 | 360 | 105+-------------+-----------------------------------+ 106| SHA-1 | 368 | 107+-------------+-----------------------------------+ 108| SHA-256 | 496 | 109+-------------+-----------------------------------+ 110| SHA-384 | 624 | 111+-------------+-----------------------------------+ 112| SHA-512 | 752 | 113+-------------+-----------------------------------+ 114 115 116 117Encryption and decryption 118-------------------------------------------------- 119 120To encrypt or decrypt a message, use :py:func:`rsa.encrypt` resp. 121:py:func:`rsa.decrypt`. Let's say that Alice wants to send a message 122that only Bob can read. 123 124#. Bob generates a keypair, and gives the public key to Alice. This is 125 done such that Alice knows for sure that the key is really Bob's 126 (for example by handing over a USB stick that contains the key). 127 128 >>> (bob_pub, bob_priv) = rsa.newkeys(512) 129 130#. Alice writes a message 131 132 >>> message = 'hello Bob!' 133 134#. Alice encrypts the message using Bob's public key, and sends the 135 encrypted message. 136 137 >>> crypto = rsa.encrypt(message, bob_pub) 138 139#. Bob receives the message, and decrypts it with his private key. 140 141 >>> message = rsa.decrypt(crypto, bob_priv) 142 >>> print message 143 hello Bob! 144 145Since Bob kept his private key *private*, Alice can be sure that he is 146the only one who can read the message. Bob does *not* know for sure 147that it was Alice that sent the message, since she didn't sign it. 148 149 150RSA can only encrypt messages that are smaller than the key. A couple 151of bytes are lost on random padding, and the rest is available for the 152message itself. For example, a 512-bit key can encode a 53-byte 153message (512 bit = 64 bytes, 11 bytes are used for random padding and 154other stuff). See :ref:`bigfiles` for information on how to work with 155larger files. 156 157Altering the encrypted information will *likely* cause a 158:py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use 159:py:func:`rsa.sign`. 160 161 >>> crypto = encrypt('hello', pub_key) 162 >>> crypto = 'X' + crypto[1:] # change the first byte 163 >>> decrypt(crypto, priv_key) 164 Traceback (most recent call last): 165 ... 166 rsa.pkcs1.DecryptionError: Decryption failed 167 168 169.. warning:: 170 171 Never display the stack trace of a 172 :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where 173 in the code the exception occurred, and thus leaks information 174 about the key. It’s only a tiny bit of information, but every bit 175 makes cracking the keys easier. 176 177Low-level operations 178++++++++++++++++++++++++++++++ 179 180The core RSA algorithm operates on large integers. These operations 181are considered low-level and are supported by the 182:py:func:`rsa.core.encrypt_int` and :py:func:`rsa.core.decrypt_int` 183functions. 184 185Signing and verification 186-------------------------------------------------- 187 188You can create a detached signature for a message using the 189:py:func:`rsa.sign` function: 190 191 >>> (pubkey, privkey) = rsa.newkeys(512) 192 >>> message = 'Go left at the blue tree' 193 >>> signature = rsa.sign(message, privkey, 'SHA-1') 194 195This hashes the message using SHA-1. Other hash methods are also 196possible, check the :py:func:`rsa.sign` function documentation for 197details. The hash is then signed with the private key. 198 199In order to verify the signature, use the :py:func:`rsa.verify` 200function. This function returns True if the verification is successful: 201 202 >>> message = 'Go left at the blue tree' 203 >>> rsa.verify(message, signature, pubkey) 204 True 205 206Modify the message, and the signature is no longer valid and a 207:py:class:`rsa.pkcs1.VerificationError` is thrown: 208 209 >>> message = 'Go right at the blue tree' 210 >>> rsa.verify(message, signature, pubkey) 211 Traceback (most recent call last): 212 File "<stdin>", line 1, in <module> 213 File "/home/sybren/workspace/python-rsa/rsa/pkcs1.py", line 289, in verify 214 raise VerificationError('Verification failed') 215 rsa.pkcs1.VerificationError: Verification failed 216 217.. warning:: 218 219 Never display the stack trace of a 220 :py:class:`rsa.pkcs1.VerificationError` exception. It shows where 221 in the code the exception occurred, and thus leaks information 222 about the key. It's only a tiny bit of information, but every bit 223 makes cracking the keys easier. 224 225Instead of a message you can also call :py:func:`rsa.sign` and 226:py:func:`rsa.verify` with a :py:class:`file`-like object. If the 227message object has a ``read(int)`` method it is assumed to be a file. 228In that case the file is hashed in 1024-byte blocks at the time. 229 230 >>> with open('somefile', 'rb') as msgfile: 231 ... signature = rsa.sign(msgfile, privkey, 'SHA-1') 232 233 >>> with open('somefile', 'rb') as msgfile: 234 ... rsa.verify(msgfile, signature, pubkey) 235 236 237.. _bigfiles: 238 239Working with big files 240-------------------------------------------------- 241 242RSA can only encrypt messages that are smaller than the key. A couple 243of bytes are lost on random padding, and the rest is available for the 244message itself. For example, a 512-bit key can encode a 53-byte 245message (512 bit = 64 bytes, 11 bytes are used for random padding and 246other stuff). 247 248How it usually works 249++++++++++++++++++++++++++++++++++++++++ 250 251The most common way to use RSA with larger files uses a block cypher 252like AES or DES3 to encrypt the file with a random key, then encrypt 253the random key with RSA. You would send the encrypted file along with 254the encrypted key to the recipient. The complete flow is: 255 256#. Generate a random key 257 258 >>> import rsa.randnum 259 >>> aes_key = rsa.randnum.read_random_bits(128) 260 261#. Use that key to encrypt the file with AES. 262#. :py:func:`Encrypt <rsa.encrypt>` the AES key with RSA 263 264 >>> encrypted_aes_key = rsa.encrypt(aes_key, public_rsa_key) 265 266#. Send the encrypted file together with ``encrypted_aes_key`` 267#. The recipient now reverses this process to obtain the encrypted 268 file. 269 270.. note:: 271 272 The Python-RSA module does not contain functionality to do the AES 273 encryption for you. 274 275Only using Python-RSA: the VARBLOCK format 276+++++++++++++++++++++++++++++++++++++++++++ 277 278As far as we know, there is no pure-Python AES encryption. Previous 279versions of Python-RSA included functionality to encrypt large files 280with just RSA, and so does this version. The format has been improved, 281though. 282 283Encrypting works as follows: the input file is split into blocks that 284are just large enough to encrypt with your RSA key. Every block is 285then encrypted using RSA, and the encrypted blocks are assembled into 286the output file. This file format is called the :ref:`VARBLOCK 287<VARBLOCK>` format. 288 289Decrypting works in reverse. The encrypted file is separated into 290encrypted blocks. Those are decrypted, and assembled into the original 291file. 292 293.. note:: 294 295 The file will get larger after encryption, as each encrypted block 296 has 8 bytes of random padding and 3 more bytes of overhead. 297 298Since these encryption/decryption functions are potentially called on 299very large files, they use another approach. Where the regular 300functions store the message in memory in its entirety, these functions 301work on one block at the time. As a result, you should call them with 302:py:class:`file`-like objects as the parameters. 303 304Before using we of course need a keypair: 305 306>>> import rsa 307>>> (pub_key, priv_key) = rsa.newkeys(512) 308 309Encryption works on file handles using the 310:py:func:`rsa.bigfile.encrypt_bigfile` function: 311 312>>> from rsa.bigfile import * 313>>> with open('inputfile', 'rb') as infile, open('outputfile', 'wb') as outfile: 314... encrypt_bigfile(infile, outfile, pub_key) 315 316As does decryption using the :py:func:`rsa.bigfile.decrypt_bigfile` 317function: 318 319>>> from rsa.bigfile import * 320>>> with open('inputfile', 'rb') as infile, open('outputfile', 'wb') as outfile: 321... decrypt_bigfile(infile, outfile, priv_key) 322 323.. note:: 324 325 :py:func:`rsa.sign` and :py:func:`rsa.verify` work on arbitrarily 326 long files, so they do not have a "bigfile" equivalent. 327 328 329