Pycryptodome
Pycryptodome
Pycryptodome
Release 3.17.0
Legrandin
1 PyCryptodome 3
2 Features 5
3 Installation 9
3.1 Compiling in Linux Ubuntu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.2 Compiling in Linux Fedora . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3 Windows (from sources) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.4 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.5 PGP verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5 API documentation 15
5.1 Crypto.Cipher package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.1.2 API principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.1.3 Symmetric ciphers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.1.4 Legacy ciphers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.2 Crypto.Signature package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.2.1 Signing a message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.2.2 Verifying a signature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.2.3 Available mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.3 Crypto.Hash package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.3.1 API principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.3.2 Attributes of hash objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.3.3 Modern hash algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.3.4 Extensible-Output Functions (XOF) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.3.5 Message Authentication Code (MAC) algorithms . . . . . . . . . . . . . . . . . . . . . . . 39
5.3.6 Historic hash algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.4 Crypto.PublicKey package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.4.1 API principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.4.2 Available key types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.4.3 Obsolete key type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.5 Crypto.Protocol package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.5.1 Key Derivation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.5.2 Secret Sharing Schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
i
5.6 Crypto.IO package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.6.1 PEM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.6.2 PKCS#8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.7 Crypto.Random package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.7.1 Crypto.Random.random module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.8 Crypto.Util package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.8.1 Crypto.Util.asn1 module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.8.2 Crypto.Util.Padding module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5.8.3 Crypto.Util.RFC1751 module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.8.4 Crypto.Util.strxor module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.8.5 Crypto.Util.Counter module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.8.6 Crypto.Util.number module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6 Examples 79
6.1 Encrypt data with AES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.2 Generate an RSA key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.3 Generate public key and private key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.4 Encrypt data with RSA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
9 Future plans 89
10 Changelog 91
10.1 3.17.0 (29 January 2023) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
10.1.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
10.1.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
10.1.3 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.2 3.16.0 (26 November 2022) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.2.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.2.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.3 3.15.0 (22 June 2022) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.3.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.3.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.4 3.14.1 (5 February 2022) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.4.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.5 3.14.0 (30 January 2022) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.5.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
10.6 3.13.0 (23 January 2022) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.6.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.6.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.6.3 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.7 3.12.0 (4 December 2021) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.7.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.7.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.8 3.11.0 (8 October 2021) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
10.8.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
ii
10.8.2 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.9 3.10.4 (25 September 2021) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.9.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.10 3.10.3 (22 September 2021) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.10.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.10.2 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.10.3 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.11 3.10.1 (9 February 2021) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.11.1 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
10.12 3.10.0 (6 February 2021) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.12.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.12.2 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.12.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.13 3.9.9 (2 November 2020) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.13.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.13.2 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.14 3.9.8 (23 June 2020) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.14.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
10.14.2 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.15 3.9.7 (20 February 2020) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.15.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.16 3.9.6 (2 February 2020) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.16.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.17 3.9.5 (1 February 2020) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.17.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.17.2 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.18 3.9.4 (18 November 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.18.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
10.19 3.9.3 (12 November 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.19.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.20 3.9.2 (10 November 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.20.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.20.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.21 3.9.1 (1 November 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.21.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.21.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.22 3.9.0 (27 August 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.22.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
10.22.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.23 3.8.2 (30 May 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.23.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.24 3.8.1 (4 April 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.24.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.24.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.25 3.8.0 (23 March 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.25.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.25.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.25.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.26 3.7.3 (19 January 2019) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.26.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.27 3.7.2 (26 November 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.27.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.28 3.7.1 (25 November 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.28.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
iii
10.28.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
10.29 3.7.0 (27 October 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.29.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.29.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.29.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.30 3.6.6 (17 August 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.30.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.31 3.6.5 (12 August 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.31.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
10.32 3.6.4 (10 July 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.32.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.32.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.33 3.6.3 (21 June 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.33.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.34 3.6.2 (19 June 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.34.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.34.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.34.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
10.35 3.6.1 (15 April 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.35.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.35.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.36 3.6.0 (8 April 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.36.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.36.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.37 3.5.1 (8 March 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.37.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.38 3.5.0 (7 March 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.38.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
10.38.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.38.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.39 3.4.12 (5 February 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.39.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.40 3.4.11 (5 February 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.40.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.41 3.4.10 (2 February 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.41.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.42 3.4.9 (1 February 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.42.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.42.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.43 3.4.8 (27 January 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.43.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.43.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.44 3.4.7 (26 August 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.44.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.44.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.45 3.4.6 (18 May 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.45.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.46 3.4.5 (6 February 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.46.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.47 3.4.4 (1 February 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.47.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.48 3.4.3 (17 October 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.48.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.49 3.4.2 (8 March 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
iv
10.49.1 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.50 3.4.1 (21 February 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.50.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.51 3.4 (7 February 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.51.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.51.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
10.51.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
10.52 3.3.1 (1 November 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.52.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.52.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.52.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.53 3.3 (29 October 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.53.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.53.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.53.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.54 3.2.1 (9 September 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.54.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.55 3.2 (6 September 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.55.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.55.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.55.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.56 3.1 (15 March 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.56.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.56.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.56.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10.57 3.0 (24 June 2014) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10.57.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10.57.2 Resolved issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10.57.3 Breaks in compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10.57.4 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
11 License 111
11.1 Public domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
11.2 BSD license . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Index 115
v
vi
PyCryptodome Documentation, Release 3.17.0
Contents 1
PyCryptodome Documentation, Release 3.17.0
2 Contents
CHAPTER 1
PyCryptodome
In this case, all modules are installed under the Crypto package.
One must avoid having both PyCrypto and PyCryptodome installed at the same time, as they will interfere with
each other.
This option is therefore recommended only when you are sure that the whole application is deployed in a
virtualenv.
2. a library independent of the old PyCrypto. You install it with:
In this case, all modules are installed under the Cryptodome package. PyCrypto and PyCryptodome can
coexist.
For faster public key operations in Unix, you should install GMP in your system.
PyCryptodome is a fork of PyCrypto. It brings the following enhancements with respect to the last official version of
PyCrypto (2.6.1):
• Authenticated encryption modes (GCM, CCM, EAX, SIV, OCB)
• Accelerated AES on Intel platforms via AES-NI
• First class support for PyPy
• Elliptic curves cryptography (NIST P-curves; Ed25519, Ed448)
3
PyCryptodome Documentation, Release 3.17.0
• Better and more compact API (nonce and iv attributes for ciphers, automatic generation of random nonces and
IVs, simplified CTR cipher mode, and more)
• SHA-3 hash algorithms (FIPS 202) and derived functions (NIST SP-800 185):
– SHAKE128 and SHA256 XOFs
– cSHAKE128 and cSHAKE256 XOFs
– KMAC128 and KMAC256
– TupleHash128 and TupleHash256
• KangarooTwelve XOF (derived from Keccak)
• Truncated hash algorithms SHA-512/224 and SHA-512/256 (FIPS 180-4)
• BLAKE2b and BLAKE2s hash algorithms
• Salsa20 and ChaCha20/XChaCha20 stream ciphers
• Poly1305 MAC
• ChaCha20-Poly1305 and XChaCha20-Poly1305 authenticated ciphers
• scrypt, bcrypt, HKDF, and NIST SP 800 108r1 Counter Mode key derivation functions
• Deterministic (EC)DSA and EdDSA
• Password-protected PKCS#8 key containers
• Shamir’s Secret Sharing scheme
• Random numbers get sourced directly from the OS (and not from a CSPRNG in userspace)
• Simplified install process, including better support for Windows
• Cleaner RSA and DSA key generation (largely based on FIPS 186-4)
• Major clean ups and simplification of the code base
PyCryptodome is not a wrapper to a separate C library like OpenSSL. To the largest possible extent, algorithms are
implemented in pure Python. Only the pieces that are extremely critical to performance (e.g. block ciphers) are
implemented as C extensions.
For more information, see the homepage.
For security issues, please send an email to [email protected].
All the code can be downloaded from GitHub.
4 Chapter 1. PyCryptodome
CHAPTER 2
Features
5
PyCryptodome Documentation, Release 3.17.0
* RSAES-PKCS1-v1_5
* RSAES-OAEP
• Asymmetric digital signatures:
– PKCS#1 (RSA)
6 Chapter 2. Features
PyCryptodome Documentation, Release 3.17.0
* RSASSA-PKCS1-v1_5
* RSASSA-PSS
– (EC)DSA
* PKCS#7
* ISO-7816
* X.923
7
PyCryptodome Documentation, Release 3.17.0
8 Chapter 2. Features
CHAPTER 3
Installation
The installation procedure depends on the package you want the library to be in. PyCryptodome can be used as:
1. An almost drop-in replacement for the old PyCrypto library. You install it with:
In this case, all modules are installed under the Crypto package. You can test everything is right with:
One must avoid having both PyCrypto and PyCryptodome installed at the same time, as they will interfere with
each other. This option is therefore recommended only when you are sure that the whole application is deployed
in a virtualenv.
2. A library independent of the old PyCrypto. You install it with:
In this case, all modules are installed under the Cryptodome package. The old PyCrypto and PyCryptodome
can coexist.
Note: If you intend to run PyCryptodome with Python 2.7 under Windows, you must first install the Microsoft Visual
C++ 2015 Redistributable. That is not necessary if you use Python 3.
The procedures below go a bit more in detail, by explaining how to setup the environment for compiling the C exten-
sions for each OS, and how to install the GMP library.
9
PyCryptodome Documentation, Release 3.17.0
Note: If you want to install under the Crypto package, replace below pycryptodomex with pycryptodome.
For PyPy:
Note: If you want to install under the Crypto package, replace below pycryptodomex with pycryptodome.
For PyPy:
10 Chapter 3. Installation
PyCryptodome Documentation, Release 3.17.0
Note: If you want to install under the Crypto package, replace below pycryptodomex with pycryptodome.
That being the case and if you want to run the test, instead of Cryptodome.SelfTest, run Crypto.SelfTest.
Windows does not come with a C compiler like most Unix systems. The simplest way to compile the PyCryptodome
extensions from source code is to install the minimum set of Visual Studio components freely made available by
Microsoft.
1. [Once only] Download Build Tools for Visual Studio 2019. In the installer, select the C++ build tools, the
Windows 10 SDK, and the latest version of MSVC v142 x64/x86 build tools.
2. Compile and install PyCryptodome:
> pip install pycryptodomex --no-binary :all:
3.4 Documentation
Project documentation is written in reStructuredText and it is stored under Doc/src. To publish it as HTML files,
you need to install sphinx and use:
> make -C Doc/ html
All source packages and wheels on PyPI are cryptographically signed. They can be verified with the following PGP
key:
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBFTXjPgBEADc3j7vnma9MXRshBPPXXenVpthQD6lrF/3XaBT2RptSf/viOD+
tz85du5XVp+r0SYYGeMNJCQ9NsztxblN/lnKgkfWRmSrB+V6QGS+e3bR5d9OIxzN
7haPxBnyRj//hCT/kKis6fa7N9wtwKBBjbaSX+9vpt7Rrt203sKfcChA4iR3EG89
TNQoc/kGGmwk/gyjfU38726v0NOhMKJp2154iQQVZ76hTDk6GkOYHTcPxdkAj4jS
Dd74M9sOtoOlyDLHOLcWNnlWGgZjtz0z0qSyFXRSuOfggTxrepWQgKWXXzgVB4Jo
0bhmXPAV8vkX5BoG6zGkYb47NGGvknax6jCvFYTCp1sOmVtf5UTVKPplFm077tQg
0KZNAvEQrdWRIiQ1cCGCoF2Alex3VmVdefHOhNmyY7xAlzpP0c8z1DsgZgMnytNn
GPusWeqQVijRxenl+lyhbkb9ZLDq7mOkCRXSze9J2+5aLTJbJu3+Wx6BEyNIHP/f
K3E77nXvC0oKaYTbTwEQSBAggAXP+7oQaA0ea2SLO176xJdNfC5lkQEtMMSZI4gN
iSqjUxXW2N5qEHHex1atmTtk4W9tQEw030a0UCxzDJMhD0aWFKq7wOxoCQ1q821R
vxBH4cfGWdL/1FUcuCMSUlc6fhTM9pvMXgjdEXcoiLSTdaHuVLuqmF/E0wARAQAB
tB9MZWdyYW5kaW4gPGhlbGRlcmlqc0BnbWFpbC5jb20+iQI4BBMBAgAiBQJU14z4
AhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRDabO+N4RaZEn7IEACpApha
vRwPB+Dv87aEyVmjZ96Nb3mxHdeP2uSmUxAODzoB5oJJ1QL6HRxEVlU8idjdf73H
(continues on next page)
12 Chapter 3. Installation
CHAPTER 4
PyCryptodome exposes almost the same API as the old PyCrypto so that most applications will run unmodified.
However, a very few breaks in compatibility had to be introduced for those parts of the API that represented a security
hazard or that were too hard to maintain.
Specifically, for public key cryptography:
• The following methods from public key objects (RSA, DSA, ElGamal) have been removed:
– sign()
– verify()
– encrypt()
– decrypt()
– blind()
– unblind()
Applications should be updated to use instead:
– Crypto.Cipher.PKCS1_OAEP for encrypting using RSA.
– Crypto.Signature.pkcs1_15 or Crypto.Signature.pss for signing using RSA.
– Crypto.Signature.DSS for signing using DSA.
• Method: generate() for public key modules does not accept the progress_func parameter anymore.
• Ambiguous method size from RSA, DSA and ElGamal key objects have been removed. Instead, use methods
size_in_bytes() and size_in_bits() and check the documentation.
• The 3 public key object types (RSA, DSA, ElGamal) are now unpickable. You must use the export_key()
method of each key object and select a good output format: for private keys that means a good password-based
encryption scheme.
• Removed attribute Crypto.PublicKey.RSA.algorithmIdentifier.
• Removed Crypto.PublicKey.RSA.RSAImplementation (which should have been private in the first
place). Same for Crypto.PublicKey.DSA.DSAImplementation.
13
PyCryptodome Documentation, Release 3.17.0
API documentation
5.1.1 Introduction
The Crypto.Cipher package contains algorithms for protecting the confidentiality of data.
There are three types of encryption algorithms:
1. Symmetric ciphers: all parties use the same key, for both decrypting and encrypting data. Symmetric ciphers
are typically very fast and can process very large amount of data.
2. Asymmetric ciphers: senders and receivers use different keys. Senders encrypt with public keys (non-secret)
whereas receivers decrypt with private keys (secret). Asymmetric ciphers are typically very slow and can process
only very small payloads. Example: oaep.
3. Hybrid ciphers: the two types of ciphers above can be combined in a construction that inherits the benefits of
both. An asymmetric cipher is used to protect a short-lived symmetric key, and a symmetric cipher (under that
key) encrypts the actual message.
15
PyCryptodome Documentation, Release 3.17.0
• For decrypting data, you call the decrypt() method of the cipher object with the ciphertext. The method
returns the piece of plaintext. The output parameter can be passed here too.
For most algorithms, you may call decrypt() multiple times (i.e. once for each piece of ciphertext).
Note: Plaintexts and ciphertexts (input/output) can only be bytes, bytearray or memoryview. In Python 3,
you cannot pass strings. In Python 2, you cannot pass Unicode strings.
Often, the sender has to deliver to the receiver other data in addition to ciphertext alone (e.g. initialization vectors or
nonces, MAC tags, etc).
This is a basic example:
A block cipher uses a symmetric key to encrypt data of fixed and very short length (the block size), such as 16 bytes
for AES. In order to cope with data of arbitrary length, the cipher must be combined with a mode of operation.
You create a cipher object with the new() function in the relevant module under Crypto.Cipher:
1. the first parameter is always the cryptographic key (a byte string)
2. the second parameter is always the constant that selects the desired mode of operation
Constants for each mode of operation are defined at the module level for each algorithm. Their name starts with
MODE_, for instance Crypto.Cipher.AES.MODE_CBC. Note that not all ciphers support all modes.
For instance:
The state machine for a cipher configured with a classic mode is:
What follows is a list of classic modes of operation: they all provide confidentiality but not data integrity (unlike
modern AEAD modes, which are described in another section).
ECB mode
Electronic CodeBook. The most basic but also the weakest mode of operation. Each block of plaintext is encrypted
independently of any other block.
Warning: The ECB mode should not be used because it is semantically insecure. For one, it exposes correlation
between blocks.
The new() function at the module level under Crypto.Cipher instantiates a new ECB cipher object for the
relevant base algorithm. In the following definition, <algorithm> could be AES:
Crypto.Cipher.<algorithm>.new(key, mode)
Create a new ECB object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
• mode – the constant Crypto.Cipher.<algorithm>.MODE_ECB
Returns an ECB cipher object
The method encrypt() (and likewise decrypt()) of an ECB cipher object expects data to have length multiple
of the block size (e.g. 16 bytes for AES). You might need to use Crypto.Util.Padding to align the plaintext to
the right boundary.
CBC mode
Ciphertext Block Chaining, defined in NIST SP 800-38A, section 6.2. It is a mode of operation where each plaintext
block gets XOR-ed with the previous ciphertext block prior to encryption.
The new() function at the module level under Crypto.Cipher instantiates a new CBC cipher object for the
relevant base algorithm. In the following definition, <algorithm> could be AES:
Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
Create a new CBC object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
• mode – the constant Crypto.Cipher.<algorithm>.MODE_CBC
• iv (bytes) – the Initialization Vector. A piece of data unpredictable to adversaries. It is
as long as the block size (e.g. 16 bytes for AES). If not present, the library creates a random
IV value.
Returns a CBC cipher object
The method encrypt() (and likewise decrypt()) of a CBC cipher object expects data to have length multiple of
the block size (e.g. 16 bytes for AES). You might need to use Crypto.Util.Padding to align the plaintext to the
right boundary.
A CBC cipher object has a read-only attribute iv, holding the Initialization Vector (bytes).
Example (encryption):
Example (decryption):
CTR mode
CounTeR mode, defined in NIST SP 800-38A, section 6.5 and Appendix B. This mode turns the block cipher into a
stream cipher. Each byte of plaintext is XOR-ed with a byte taken from a keystream: the result is the ciphertext. The
keystream is generated by encrypting a sequence of counter blocks with ECB.
A counter block is exactly as long as the cipher block size (e.g. 16 bytes for AES). It consists of the concatenation of
two pieces:
1. a fixed nonce, set at initialization.
2. a variable counter, which gets increased by 1 for any subsequent counter block. The counter is big endian
encoded.
The new() function at the module level under Crypto.Cipher instantiates a new CTR cipher object for the
relevant base algorithm. In the following definition, <algorithm> could be AES:
Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, initial_value=None, counter=None)
Create a new CTR object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
Example (decryption):
CFB mode
Cipher FeedBack, defined in NIST SP 800-38A, section 6.3. It is a mode of operation which turns the block cipher
into a stream cipher. Each byte of plaintext is XOR-ed with a byte taken from a keystream: the result is the ciphertext.
The keystream is obtained on a per-segment basis: the plaintext is broken up in segments (from 1 byte up to the size
of a block). Then, for each segment, the keystream is obtained by encrypting with the block cipher the last piece of
ciphertext produced so far - possibly backfilled with the Initialization Vector, if not enough ciphertext is available yet.
The new() function at the module level under Crypto.Cipher instantiates a new CFB cipher object for the
relevant base algorithm. In the following definition, <algorithm> could be AES:
Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None, segment_size=8)
Create a new CFB object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
• mode – the constant Crypto.Cipher.<algorithm>.MODE_CFB
• iv (bytes) – the Initialization Vector. It must be unique for the combination message/key.
It is as long as the block size (e.g. 16 bytes for AES). If not present, the library creates a
random IV.
• segment_size (integer) – the number of bits (not bytes!) the plaintext and the ci-
phertext are segmented in (default if not specified: 8 bits = 1 byte).
Returns a CFB cipher object
The methods encrypt() and decrypt() of a CFB cipher object accept data of any length (i.e. padding is not
needed).
The CFB cipher object has a read-only attribute iv (bytes), holding the Initialization Vector.
Example (encryption):
Example (decryption):
OFB mode
Output FeedBack, defined in NIST SP 800-38A, section 6.4. It is another mode that leads to a stream cipher. Each
byte of plaintext is XOR-ed with a byte taken from a keystream: the result is the ciphertext. The keystream is obtained
by recursively encrypting the Initialization Vector.
The new() function at the module level under Crypto.Cipher instantiates a new OFB cipher object for the
relevant base algorithm. In the following definition, <algorithm> could be AES:
Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
Create a new OFB object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
• mode – the constant Crypto.Cipher.<algorithm>.MODE_OFB
• iv (bytes) – the Initialization Vector. It must be unique for the combination message/key.
It is as long as the block size (e.g. 16 bytes for AES). If not present, the library creates a
random IV.
Returns an OFB cipher object
The methods encrypt() and decrypt() of an OFB cipher object accept data of any length (i.e. padding is not
needed).
The OFB cipher object has a read-only attribute iv (bytes), holding the Initialization Vector.
Example (encryption):
>>> import json
>>> from base64 import b64encode
>>> from Crypto.Cipher import AES
>>> from Crypto.Random import get_random_bytes
>>>
>>> data = b"secret"
>>> key = get_random_bytes(16)
>>> cipher = AES.new(key, AES.MODE_OFB)
>>> ct_bytes = cipher.encrypt(data)
>>> iv = b64encode(cipher.iv).decode('utf-8')
>>> ct = b64encode(ct_bytes).decode('utf-8')
>>> result = json.dumps({'iv':iv, 'ciphertext':ct})
>>> print(result)
{"iv": "NUuRJbL0UMp8+UMCk2/vQA==", "ciphertext": "XGVGc1Gw"}
Example (decryption):
>>> import json
>>> from base64 import b64decode
>>> from Crypto.Cipher import AES
>>>
>>> # We assume that the key was securely shared beforehand
>>> try:
>>> b64 = json.loads(json_input)
(continues on next page)
OpenPGP mode
Constant: Crypto.Cipher.<cipher>.MODE_OPENPGP.
OpenPGP (defined in RFC4880). A variant of CFB, with two differences:
1. The first invocation to the encrypt() method returns the encrypted IV concatenated to the first chunk of
ciphertext (as opposed to the ciphertext only). The encrypted IV is as long as the block size plus 2 more bytes.
2. When the cipher object is intended for decryption, the parameter iv to new() is the encrypted IV (and not the
IV, which is still the case for encryption).
Like for CTR, an OpenPGP cipher object has a read-only attribute iv.
Classic modes of operation such as CBC only provide guarantees over the confidentiality of the message but not over
its integrity. In other words, they don’t allow the receiver to establish if the ciphertext was modified in transit or if it
really originates from a certain source.
For that reason, classic modes of operation have been often paired with a MAC primitive (such as Crypto.Hash.
HMAC), but the combination is not always straightforward, efficient or secure.
Recently, new modes of operations (AEAD, for Authenticated Encryption with Associated Data) have been designed
to combine encryption and authentication into a single, efficient primitive. Optionally, some part of the message can
also be left in the clear (non-confidential associated data, such as headers), while the whole message remains fully
authenticated.
In addition to the ciphertext and a nonce (or IV - Initialization Vector), AEAD modes require the additional delivery
of a MAC tag.
This is the state machine for a cipher object:
Beside the usual encrypt() and decrypt() already available for classic modes of operation, several other meth-
ods are present:
update(data)
Authenticate those parts of the message that get delivered as is, without any encryption (like headers). It is
similar to the update() method of a MAC object. Note that all data passed to encrypt() and decrypt()
get automatically authenticated already.
Parameters data (bytes) – the extra data to authenticate
digest()
Create the final authentication tag (MAC tag) for a message.
Return bytes the MAC tag
hexdigest()
Equivalent to digest(), with the output encoded in hexadecimal.
CCM mode
Counter with CBC-MAC, defined in RFC3610 or NIST SP 800-38C. It only works with ciphers having block size 128
bits (like AES).
The new() function at the module level under Crypto.Cipher instantiates a new CCM cipher object for the
relevant base algorithm. In the following definition, <algorithm> can only be AES today:
Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None, msg_len=None, assoc_l
Create a new CCM object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
• mode – the constant Crypto.Cipher.<algorithm>.MODE_CCM
• nonce (bytes) – the value of the fixed nonce. It must be unique for the combination
message/key. For AES, its length varies from 7 to 13 bytes. The longer the nonce, the
smaller the allowed message size (with a nonce of 13 bytes, the message cannot exceed
64KB). If not present, the library creates a 11 bytes random nonce (the maximum message
size is 8GB).
• mac_len (integer) – the desired length of the MAC tag (default if not present: 16
bytes).
• msg_len (integer) – pre-declaration of the length of the message to encipher. If not
specified, encrypt() and decrypt() can only be called once.
• assoc_len (integer) – pre-declaration of the length of the associated data. If not
specified, some extra buffering will take place internally.
Returns a CTR cipher object
The cipher object has a read-only attribute nonce.
Example (encryption):
>>> import json
>>> from base64 import b64encode
>>> from Crypto.Cipher import AES
>>> from Crypto.Random import get_random_bytes
>>>
>>> header = b"header"
>>> data = b"secret"
>>> key = get_random_bytes(16)
>>> cipher = AES.new(key, AES.MODE_CCM)
(continues on next page)
Example (decryption):
EAX mode
An AEAD mode designed for NIST by Bellare, Rogaway, and Wagner in 2003.
The new() function at the module level under Crypto.Cipher instantiates a new EAX cipher object for the
relevant base algorithm.
Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
Create a new EAX object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
• mode – the constant Crypto.Cipher.<algorithm>.MODE_EAX
• nonce (bytes) – the value of the fixed nonce. It must be unique for the combination
message/key. If not present, the library creates a random nonce (16 bytes long for AES).
• mac_len (integer) – the length of the MAC tag, in bytes. At least 2, and not larger than
the cipher’s block size (default), which is 16 bytes for AES.
Returns an EAX cipher object
The cipher object has a read-only attribute nonce.
Example (encryption):
Example (decryption):
GCM mode
Galois/Counter Mode, defined in NIST SP 800-38D. It only works in combination with a 128 bits cipher like AES.
The new() function at the module level under Crypto.Cipher instantiates a new GCM cipher object for the
relevant base algorithm.
Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
Create a new GCM object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key
• mode – the constant Crypto.Cipher.<algorithm>.MODE_GCM
• nonce (bytes) – the value of the fixed nonce. It must be unique for the combination
message/key. If not present, the library creates a random nonce (16 bytes long for AES).
• mac_len (integer) – the desired length of the MAC tag, from 4 to 16 bytes (default:
16).
Returns a GCM cipher object
The cipher object has a read-only attribute nonce.
Example (encryption):
Example (decryption):
Note: GCM is most commonly used with 96-bit (12-byte) nonces, which is also the length recommended by NIST
SP 800-38D.
If interoperability is important, one should take into account that the library default of a 128-bit random nonce may
not be (easily) supported by other implementations. A 96-bit nonce can be explicitly generated for a new encryption
cipher:
SIV mode
Synthetic Initialization Vector (SIV), defined in RFC5297. It only works with ciphers with a block size of 128 bits
(like AES).
Although less efficient than other modes, SIV is nonce misuse-resistant: accidental reuse of the nonce does not jeop-
ardize the security as it happens with CCM or GCM. As a matter of fact, operating without a nonce is not an error
per se: the cipher simply becomes deterministic. In other words, a message gets always encrypted into the same
ciphertext.
The new() function at the module level under Crypto.Cipher instantiates a new SIV cipher object for the relevant
base algorithm.
Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None)
Create a new SIV object, using <algorithm> as the base block cipher.
Parameters
• key (bytes) – the cryptographic key; it must be twice the size of the key required by the
underlying cipher (e.g. 32 bytes for AES-128).
• mode – the constant Crypto.Cipher.<algorithm>.MODE_SIV
• nonce (bytes) – the value of the fixed nonce. It must be unique for the combination
message/key. If not present, the encryption will be deterministic.
Returns a SIV cipher object
If the nonce parameter was provided to new(), the resulting cipher object has a read-only attribute nonce.
Example (encryption):
Example (decryption):
One side-effect is that encryption (or decryption) must take place in one go with the method
encrypt_and_digest() (or decrypt_and_verify()). You cannot use encrypt() or decrypt().
The state diagram is therefore:
The length of the key passed to new() must be twice as required by the underlying block cipher (e.g. 32 bytes for
AES-128).
Each call to the method update() consumes an full piece of associated data. That is, the sequence:
>>> siv_cipher.update(b"builtin")
>>> siv_cipher.update(b"securely")
OCB mode
Offset CodeBook mode, a cipher designed by Rogaway and specified in RFC7253 (more specifically, this module
implements the last variant, OCB3). It only works in combination with a 128 bits cipher like AES.
OCB was patented in USA but the author eventually abandoned the patents.
The new() function at the module level under Crypto.Cipher instantiates a new OCB cipher object for the
relevant base algorithm.
Note: The OCB state machine is slightly different compared to other modes: if you encrypt (or decrypt) multiple
chunks, at the end you MUST call the method encrypt (or decrypt) with no parameters. This last call will return
any piece of internally cached ciphertext (or plaintext).
A number of ciphers are implemented in this library purely for backward compatibility purposes. They are deprecated
or even fully broken and should not be used in new designs.
The Crypto.Signature package contains algorithms for performing digital signatures, used to guarantee integrity
and non-repudiation.
Digital signatures are based on public key cryptography: the party that signs a message holds the private key, the one
that verifies the signature holds the public key.
1. Instantiate a new signer object for the desired algorithm, for instance with Crypto.Signature.
pkcs1_15.new(). The first parameter is the key object (private key) obtained via the Crypto.
PublicKey module.
2. Instantiate a cryptographic hash object, for instance with Crypto.Hash.SHA384.new(). Then, process
the message with its update() method.
3. Invoke the sign() method on the signer with the hash object as parameter. The output is the signature of the
message (a byte string).
1. Instantiate a new verifier object for the desired algorithm, for instance with Crypto.Signature.
pkcs1_15.new(). The first parameter is the key object (public key) obtained via the Crypto.PublicKey
module.
2. Instantiate a cryptographic hash object, for instance with Crypto.Hash.SHA384.new(). Then, process
the message with its update() method.
3. Invoke the verify() method on the verifier, with the hash object and the incoming signature as parameters.
If the message is not authentic, an ValueError is raised.
• pkcs1_v1_5
• pkcs1_pss
• eddsa
• dsa
Cryptographic hash functions take arbitrary binary strings as input, and produce a random-like fixed-length output
(called digest or hash value).
It is practically infeasible to derive the original input data from the digest. In other words, the cryptographic hash
function is one-way (pre-image resistance).
Given the digest of one message, it is also practically infeasible to find another message (second pre-image) with the
same digest (weak collision resistance).
Finally, it is infeasible to find two arbitrary messages with the same digest (strong collision resistance).
Regardless of the hash algorithm, an n bits long digest is at most as secure as a symmetric encryption algorithm keyed
with n/2 bits (birthday attack).
Hash functions can be simply used as integrity checks. In combination with a public-key algorithm, you can implement
a digital signature.
Every time you want to hash a message, you have to create a new hash object with the new() function in the relevant
algorithm module (e.g. Crypto.Hash.SHA256.new()).
A first piece of message to hash can be passed to new() with the data parameter:
Note: You can only hash byte strings or byte arrays (no Python 2 Unicode strings or Python 3 strings).
Afterwards, the method update() can be invoked any number of times as necessary, with other pieces of message:
>>> hash_object.update(b'Second')
>>> hash_object.update(b'Third')
>>> hash_object.update(b'SecondThird')
At the end, the digest can be retrieved with the methods digest() or hexdigest():
>>> print(hash_object.digest())
b'}\x96\xfd@\xb2$?O\xca\xc1a\x10\x15\x8c\x94\xe4\xb4\x085"\xd5
˓→"\xa8\xa4C\x9e+\x00\x859\xc7A'
>>> print(hash_object.hexdigest())
7d96fd40b2243f4fcac16110158c94e4b4083522d522a8a4439e2b008539c741
Attribute Description
digest_size Size of the digest in bytes, that is, the output of the digest() method. It does not exist
for hash functions with variable digest output (such as Crypto.Hash.SHAKE128). This
is also a module attribute.
block_size The size of the message block in bytes, input to the compression function. Only appli-
cable for algorithms based on the Merkle-Damgard construction (e.g. Crypto.Hash.
SHA256). This is also a module attribute.
oid A string with the dotted representation of the ASN.1 OID assigned to the hash algorithm.
A XOF is similar to a conventional cryptographic hash: it is a one-way function that maps a piece of data of arbitrary
size to a random-like output. It provides some guarantees over collision resistance, pre-image resistance, and second
pre-image resistance.
Unlike a conventional hash, an application using a XOF can choose the length of the output. For this reason, a XOF
does not have a digest() method. Instead, it has a read(N) method to extract the next N bytes of the output.
– cshake256
• k12
• hmac
• cmac
• poly1305
• SHA-3 derived functions (NIST SP 800-185)
– kmac128
– kmac256
In a public key cryptography system, senders and receivers do not use the same key. Instead, the system defines a key
pair, with one of the keys being confidential (private) and the other not (public).
Unlike keys meant for symmetric cipher algorithms (typically just random bit strings), keys for public key algorithms
have very specific properties. This module collects all methods to generate, validate, store and retrieve public keys.
Asymmetric keys are represented by Python objects. Each object can be either a private key or a public key (the
method has_private() can be used to distinguish them).
A key object can be created in four ways:
1. generate() at the module level (e.g. Crypto.PublicKey.RSA.generate()). The key is randomly
created each time.
2. import_key() at the module level (e.g. Crypto.PublicKey.RSA.import_key()). The key is
loaded from memory.
RSA
RSA is the most widespread and used public key algorithm. Its security is based on the difficulty of factoring large
integers. The algorithm has withstood attacks for more than 30 years, and it is therefore considered reasonably secure
for new designs.
The algorithm can be used for both confidentiality (encryption) and authentication (digital signature). It is worth
noting that signing and decryption are significantly slower than verification and encryption.
The cryptographic strength is primarily linked to the length of the RSA modulus n. In 2017, a sufficient length is
deemed to be 2048 bits. For more information, see the most recent ECRYPT report.
Both RSA ciphertexts and RSA signatures are as large as the RSA modulus n (256 bytes if n is 2048 bit long).
The module Crypto.PublicKey.RSA provides facilities for generating new RSA keys, reconstructing them from
known components, exporting them, and importing them.
As an example, this is how you generate a new RSA key pair, save it in a file called mykey.pem, and then read it
back:
𝑝*𝑞 =𝑛 (5.1)
𝑒 * 𝑑 ≡ 1(mod lcm[(𝑝 − 1)(𝑞 −(5.2)
1)])
𝑝 * 𝑢 ≡ 1(mod 𝑞)
(5.3)
Parameters
• rsa_components (tuple) – A tuple of integers, with at least 2 and no more than 6
items. The items come in the following order:
1. RSA modulus n.
2. Public exponent e.
3. Private exponent d. Only required if the key is private.
4. First factor of n (p). Optional, but the other factor q must also be present.
5. Second factor of n (q). Optional.
6. CRT coefficient q, that is 𝑝−1 mod 𝑞. Optional.
• consistency_check (boolean) – If True, the library will verify that the provided
components fulfil the main RSA properties.
Raises ValueError – when the key being imported fails the most basic RSA validity checks.
Returns: An RSA key object (RsaKey).
Crypto.PublicKey.RSA.import_key(extern_key, passphrase=None)
Import an RSA key (public or private).
Parameters
• extern_key (string or byte string) – The RSA key to import.
The following formats are supported for an RSA public key:
– X.509 certificate (binary or PEM format)
– X.509 subjectPublicKeyInfo DER SEQUENCE (binary or PEM encoding)
– PKCS#1 RSAPublicKey DER SEQUENCE (binary or PEM encoding)
– An OpenSSH line (e.g. the content of ~/.ssh/id_ecdsa, ASCII)
The following formats are supported for an RSA private key:
– PKCS#1 RSAPrivateKey DER SEQUENCE (binary or PEM encoding)
– PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo DER SEQUENCE
(binary or PEM encoding)
– OpenSSH (text format, introduced in OpenSSH 6.5)
For details about the PEM encoding, see RFC1421/RFC1423.
• passphrase (string or byte string) – For private keys only, the pass phrase
that encrypts the key.
Returns: An RSA key object (RsaKey).
Raises ValueError/IndexError/TypeError – When the given key cannot be parsed (pos-
sibly because the pass phrase is wrong).
class Crypto.PublicKey.RSA.RsaKey(**kwargs)
Class defining an actual RSA key. Do not instantiate directly. Use generate(), construct() or
import_key() instead.
Variables
• n (integer) – RSA modulus
• e (integer) – RSA public exponent
• d (integer) – RSA private exponent
• p (integer) – First factor of the RSA modulus
• q (integer) – Second factor of the RSA modulus
• invp (integer) – Chinese remainder component (𝑝−1 mod 𝑞)
• invq (integer) – Chinese remainder component (𝑞 −1 mod 𝑝)
• u (integer) – Same as invp
Undocumented exportKey, publickey
exportKey(format=’PEM’, passphrase=None, pkcs=1, protection=None, randfunc=None)
Export this RSA key.
Parameters
• format (string) – The format to use for wrapping the key:
– ’PEM’. (Default) Text encoding, done according to RFC1421/RFC1423.
– ’DER’. Binary encoding.
– ’OpenSSH’. Textual encoding, done according to OpenSSH specification. Only suitable
for public keys (not private keys).
• passphrase (string) – (For private keys only) The pass phrase used for protecting
the output.
• pkcs (integer) – (For private keys only) The ASN.1 structure to use for serializing the
key. Note that even in case of PEM encoding, there is an inner ASN.1 DER structure.
With pkcs=1 (default), the private key is encoded in a simple PKCS#1 structure
(RSAPrivateKey).
With pkcs=8, the private key is encoded in a PKCS#8 structure (PrivateKeyInfo).
Note: This parameter is ignored for a public key. For DER and PEM, an ASN.1 DER
SubjectPublicKeyInfo structure is always used.
• protection (string) – (For private keys only) The encryption scheme to use for
protecting the private key.
If None (default), the behavior depends on format:
Warning: If you don’t provide a pass phrase, the private key will be exported in the clear!
Note: This parameter is ignored for a public key. For DER and PEM, an ASN.1
DER SubjectPublicKeyInfo structure is always used.
• protection (string) – (For private keys only) The encryption scheme to use for
protecting the private key.
If None (default), the behavior depends on format:
– For ‘DER’, the PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC scheme is used.
The following operations are performed:
1. A 16 byte Triple DES key is derived from the passphrase using Crypto.
Protocol.KDF.PBKDF2() with 8 bytes salt, and 1 000 iterations of
Crypto.Hash.HMAC.
2. The private key is encrypted using CBC.
3. The encrypted key is encoded according to PKCS#8.
– For ‘PEM’, the obsolete PEM encryption scheme is used. It is based on MD5 for
key derivation, and Triple DES for encryption.
Specifying a value for protection is only meaningful for PKCS#8 (that is,
pkcs=8) and only if a pass phrase is present too.
The supported schemes for PKCS#8 are listed in the Crypto.IO.PKCS8 module
(see wrap_algo parameter).
• randfunc (callable) – A function that provides random bytes. Only used for
PEM encoding. The default is Crypto.Random.get_random_bytes().
Returns the encoded key
Return type byte string
Raises ValueError – when the format is unknown or when you try to encrypt a private key
with DER format and PKCS#1.
Warning: If you don’t provide a pass phrase, the private key will be exported in the clear!
has_private()
Whether this is an RSA private key
public_key()
A matching RSA public key.
Returns a new RsaKey object
publickey()
A matching RSA public key.
Returns a new RsaKey object
size_in_bits()
Size of the RSA modulus in bits
size_in_bytes()
The minimal amount of bytes that can hold the RSA modulus
Crypto.PublicKey.RSA.oid = '1.2.840.113549.1.1.1'
Object ID for the RSA encryption algorithm. This OID often indicates a generic RSA key, even when such key
will be actually used for digital signatures.
DSA
DSA is a widespread public key signature algorithm. Its security is based on the discrete logarithm problem (DLP).
Given a cyclic group, a generator g, and an element h, it is hard to find an integer x such that 𝑔 𝑥 = ℎ. The problem is
believed to be difficult, and it has been proved such (and therefore secure) for more than 30 years.
The group is actually a sub-group over the integers modulo p, with p prime. The sub-group order is q, which is prime
too; it always holds that (p-1) is a multiple of q. The cryptographic strength is linked to the magnitude of p and q. The
signer holds a value x (0<x<q-1) as private key, and its public key (y where 𝑦 = 𝑔 𝑥 mod 𝑝) is distributed.
In 2017, a sufficient size is deemed to be 2048 bits for p and 256 bits for q. For more information, see the most recent
ECRYPT report.
The algorithm can only be used for authentication (digital signature). DSA cannot be used for confidentiality (encryp-
tion).
The values (p,q,g) are called domain parameters; they are not sensitive but must be shared by both parties (the signer
and the verifier). Different signers can share the same domain parameters with no security concerns.
The DSA signature is twice as big as the size of q (64 bytes if q is 256 bit long).
This module provides facilities for generating new DSA keys and for constructing them from known components.
As an example, this is how you generate a new DSA key pair, save the public key in a file called public_key.pem,
sign a message (with Crypto.Signature.DSS), and verify it:
Parameters
• bits (integer) – Key length, or size (in bits) of the DSA modulus p. It must be 1024,
2048 or 3072.
• randfunc (callable) – Random number generation function; it accepts a single
integer N and return a string of random data N bytes long. If not specified, Crypto.
Random.get_random_bytes() is used.
• domain (tuple) – The DSA domain parameters p, q and g as a list of 3 integers. Size
of p and q must comply to FIPS 186-4. If not specified, the parameters are created anew.
Returns a new DSA key object
Return type DsaKey
Raises ValueError – when bits is too little, too big, or not a multiple of 64.
Crypto.PublicKey.DSA.construct(tup, consistency_check=True)
Construct a DSA key from a tuple of valid DSA components.
Parameters
• tup (tuple) – A tuple of long integers, with 4 or 5 items in the following order:
1. Public key (y).
2. Sub-group generator (g).
3. Modulus, finite field order (p).
4. Sub-group order (q).
5. Private key (x). Optional.
• consistency_check (boolean) – If True, the library will verify that the provided
components fulfil the main DSA properties.
Raises ValueError – when the key being imported fails the most basic DSA validity checks.
Returns a DSA key object
Return type DsaKey
class Crypto.PublicKey.DSA.DsaKey(key_dict)
Class defining an actual DSA key. Do not instantiate directly. Use generate(), construct() or
import_key() instead.
Variables
• p (integer) – DSA modulus
• q (integer) – Order of the subgroup
• g (integer) – Generator
• y (integer) – Public key
• x (integer) – Private key
Undocumented exportKey, publickey
domain()
The DSA domain parameters.
Returns tuple : (p,q,g)
Warning: If you don’t provide a pass phrase, the private key will be exported in the clear!
Warning: If you don’t provide a pass phrase, the private key will be exported in the clear!
has_private()
Whether this is a DSA private key
public_key()
A matching DSA public key.
Returns a new DsaKey object
publickey()
A matching DSA public key.
Returns a new DsaKey object
Crypto.PublicKey.DSA.import_key(extern_key, passphrase=None)
Import a DSA key.
Parameters
• extern_key (string or byte string) – The DSA key to import.
The following formats are supported for a DSA public key:
– X.509 certificate (binary DER or PEM)
– X.509 subjectPublicKeyInfo (binary DER or PEM)
– OpenSSH (ASCII one-liner, see RFC4253)
The following formats are supported for a DSA private key:
– PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo DER SE-
QUENCE (binary or PEM)
– OpenSSL/OpenSSH custom format (binary or PEM)
For details about the PEM encoding, see RFC1421/RFC1423.
• passphrase (string) – In case of an encrypted private key, this is the pass phrase
from which the decryption key is derived.
Encryption may be applied either at the PKCS#8 or at the PEM level.
Returns a DSA key object
Return type DsaKey
Raises ValueError – when the given key cannot be parsed (possibly because the pass phrase is
wrong).
ECC
ECC (Elliptic Curve Cryptography) is a modern and efficient type of public key cryptography. Its security is based on
the difficulty to solve discrete logarithms on the field defined by specific equations computed over a curve.
ECC can be used to create digital signatures or to perform a key exchange.
Compared to traditional algorithms like RSA, an ECC key is significantly smaller at the same security level. For
instance, a 3072-bit RSA key takes 768 bytes whereas the equally strong NIST P-256 private key only takes 32 bytes
(that is, 256 bits).
This module provides mechanisms for generating new ECC keys, exporting and importing them using widely sup-
ported formats like PEM or DER.
For more information about each NIST curve see FIPS 186-4, Section D.1.2.
The Ed25519 and the Ed448 curves are defined in RFC8032.
The following example demonstrates how to generate a new ECC key, export it, and subsequently reload it back into
the application:
>>> from Crypto.PublicKey import ECC
>>>
>>> key = ECC.generate(curve='P-256')
>>>
>>> f = open('myprivatekey.pem','wt')
>>> f.write(key.export_key(format='PEM'))
>>> f.close()
...
>>> f = open('myprivatekey.pem','rt')
>>> key = ECC.import_key(f.read())
The ECC key can be used to perform or verify signatures, using the modules Crypto.Signature.DSS (ECDSA;
NIST curves only) or Crypto.Signature.eddsa (EdDSA; Ed25519 and Ed448 curve only).
class Crypto.PublicKey.ECC.EccKey(**kwargs)
Class defining an ECC key. Do not instantiate directly. Use generate(), construct() or
import_key() instead.
Variables
• curve (string) – The name of the curve as defined in the ECC table.
• pointQ (EccPoint) – an ECC point representating the public component.
• d (integer) – A scalar that represents the private component in NIST P curves. It is
smaller than the order of the generator point.
• seed (bytes) – A seed that representats the private component in EdDSA curves
(Ed25519, 32 bytes; Ed448, 57 bytes).
export_key(**kwargs)
Export this ECC key.
Parameters
• format (string) – The format to use for encoding the key:
– 'DER'. The key will be encoded in ASN.1 DER format (binary). For a public
key, the ASN.1 subjectPublicKeyInfo structure defined in RFC5480 will be
used. For a private key, the ASN.1 ECPrivateKey structure defined in RFC5915
is used instead (possibly within a PKCS#8 envelope, see the use_pkcs8 flag
below).
– 'PEM'. The key will be encoded in a PEM envelope (ASCII).
– 'OpenSSH'. The key will be encoded in the OpenSSH format (ASCII, public keys
only).
– 'SEC1'. The public key (i.e., the EC point) will be encoded into bytes according
to Section 2.3.3 of SEC1 (which is a subset of the older X9.62 ITU standard). Only
for NIST P-curves.
– 'raw'. The public key will be encoded as bytes, without any metadata.
Warning: If you don’t provide a passphrase, the private key will be exported in the clear!
Note: When exporting a private key with password-protection and PKCS#8 (both DER and PEM formats),
any extra parameters to export_key() will be passed to Crypto.IO.PKCS8.
Returns A multi-line string (for 'PEM' and 'OpenSSH') or bytes (for 'DER', 'SEC1',
and 'raw') with the encoded key.
has_private()
True if this key can be used for making signatures or decrypting data.
public_key()
A matching ECC public key.
Returns a new EccKey object
class Crypto.PublicKey.ECC.EccPoint(x, y, curve=’p256’)
A class to model a point on an Elliptic Curve.
The class supports operators for:
• Adding two points: R = S + T
• In-place addition: S += T
• Negating a point: R = -T
• Comparing two points: if S == T: ... or if S != T: ...
• Multiplying a point by a scalar: R = S*k
• In-place multiplication by a scalar: T *= k
Variables
• x (integer) – The affine X-coordinate of the ECC point
• y (integer) – The affine Y-coordinate of the ECC point
• xy – The tuple with affine X- and Y- coordinates
copy()
Return a copy of this point.
double()
Double this point (in-place operation).
Returns This same object (to enable chaining).
is_point_at_infinity()
True if this is the point-at-infinity.
point_at_infinity()
Return the point-at-infinity for the curve.
size_in_bits()
Size of each coordinate, in bits.
size_in_bytes()
Size of each coordinate, in bytes.
exception Crypto.PublicKey.ECC.UnsupportedEccFeature
Crypto.PublicKey.ECC.construct(**kwargs)
Build a new ECC key (private or public) starting from some base components.
In most cases, you will already have an existing key which you can read in with import_key() instead of
this function.
Parameters
• curve (string) – Mandatory. The name of the elliptic curve, as defined in the ECC
table.
• d (integer) – Mandatory for a private key and a NIST P-curve (e.g., P-256): the integer
in the range [1..order-1] that represents the key.
• seed (bytes) – Mandatory for a private key and an EdDSA curve. It must be 32 bytes
for Ed25519, and 57 bytes for Ed448.
• point_x (integer) – Mandatory for a public key: the X coordinate (affine) of the
ECC point.
• point_y (integer) – Mandatory for a public key: the Y coordinate (affine) of the
ECC point.
Returns a new ECC key object
Return type EccKey
Crypto.PublicKey.ECC.generate(**kwargs)
Generate a new private key on the given curve.
Parameters
• curve (string) – Mandatory. It must be a curve name defined in the ECC table.
• randfunc (callable) – Optional. The RNG to read randomness from. If None,
Crypto.Random.get_random_bytes() is used.
Crypto.PublicKey.ECC.import_key(encoded, passphrase=None, curve_name=None)
Import an ECC key (public or private).
Parameters
• encoded (bytes or multi-line string) – The ECC key to import. The func-
tion will try to automatically detect the right format.
Supported formats for an ECC public key:
– X.509 certificate: binary (DER) or ASCII (PEM).
– X.509 subjectPublicKeyInfo: binary (DER) or ASCII (PEM).
– SEC1 (or X9.62), as bytes. NIST P curves only. You must also provide the
curve_name (with a value from the ECC table)
– OpenSSH line, defined in RFC5656 and RFC8709 (ASCII). This is normally the
content of files like ~/.ssh/id_ecdsa.pub.
Supported formats for an ECC private key:
– A binary ECPrivateKey structure, as defined in RFC5915 (DER). NIST P curves
only.
– A PKCS#8 structure (or the more recent Asymmetric Key Package, RFC5958): bi-
nary (DER) or ASCII (PEM).
– OpenSSH 6.5 and newer versions (ASCII).
Note: To import EdDSA private and public keys, when encoded as raw bytes, use:
• Crypto.Signature.eddsa.import_public_key(), or
• Crypto.Signature.eddsa.import_private_key().
El Gamal
Warning: Even though ElGamal algorithms are in theory reasonably secure, in practice there are no real good
reasons to prefer them to RSA instead.
Signature algorithm
The security of the ElGamal signature scheme is based (like DSA) on the discrete logarithm problem (DLP). Given a
cyclic group, a generator g, and an element h, it is hard to find an integer x such that 𝑔 𝑥 = ℎ.
The group is the largest multiplicative sub-group of the integers modulo p, with p prime. The signer holds a value x
(0<x<p-1) as private key, and its public key (y where 𝑦 = 𝑔 𝑥 mod 𝑝) is distributed.
The ElGamal signature is twice as big as p.
Encryption algorithm
The security of the ElGamal encryption scheme is based on the computational Diffie-Hellman problem (CDH). Given
a cyclic group, a generator g, and two integers a and b, it is difficult to find the element 𝑔 𝑎𝑏 when only 𝑔 𝑎 and 𝑔 𝑏 are
known, and not a and b.
As before, the group is the largest multiplicative sub-group of the integers modulo p, with p prime. The receiver holds
a value a (0<a<p-1) as private key, and its public key (b where 𝑏 = 𝑔 𝑎 ) is given to the sender.
The ElGamal ciphertext is twice as big as p.
Domain parameters
For both signature and encryption schemes, the values (p,g) are called domain parameters. They are not sensitive but
must be distributed to all parties (senders and receivers). Different signers can share the same domain parameters, as
can different recipients of encrypted messages.
Security
Both DLP and CDH problem are believed to be difficult, and they have been proved such (and therefore secure) for
more than 30 years.
The cryptographic strength is linked to the magnitude of p. In 2017, a sufficient size for p is deemed to be 2048 bits.
For more information, see the most recent ECRYPT report.
The signature is four times larger than the equivalent DSA, and the ciphertext is two times larger than the equivalent
RSA.
Functionality
This module provides facilities for generating new ElGamal keys and constructing them from known components.
Crypto.PublicKey.ElGamal.generate(bits, randfunc)
Randomly generate a fresh, new ElGamal key.
The key will be safe for use for both encryption and signature (although it should be used for only one purpose).
Parameters
• bits (int) – Key length, or size (in bits) of the modulus p. The recommended value is
2048.
• randfunc (callable) – Random number generation function; it should accept a sin-
gle integer N and return a string of random N random bytes.
Returns an ElGamalKey object
Crypto.PublicKey.ElGamal.construct(tup)
Construct an ElGamal key from a tuple of valid ElGamal components.
The modulus p must be a prime. The following conditions must apply:
Parameters tup (tuple) – A tuple with either 3 or 4 integers, in the following order:
1. Modulus (p).
2. Generator (g).
3. Public key (y).
PBKDF2
PBKDF2 is the most widespread algorithm for deriving keys from a password, originally defined in version 2.0 of the
PKCS#5 standard or in RFC2898.
It is computationally expensive (a property that can be tuned via the count parameter) so as to thwart dictionary and
rainbow tables attacks. However, it uses a very limited amount of RAM which makes it insufficiently protected against
advanced and motivated adversaries that can leverage GPUs.
New applications and protocols should use scrypt or bcrypt instead.
For example, if you need to derive two AES256 keys:
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Hash import SHA512
from Crypto.Random import get_random_bytes
scrypt
scrypt is a password-based key derivation function created by Colin Percival, described in his paper “Stronger key
derivation via sequential memory-hard functions” and in RFC7914.
In addition to being computationally expensive, it is also memory intensive and therefore more secure against the risk
of custom ASICs.
Example:
bcrypt
bcrypt is a password hashing function designed by Niels Provos and David Mazières.
In addition to being computationally expensive, it is also memory intensive and therefore more secure against the risk
of custom ASICs.
This implementation only supports bcrypt hashes with prefix $2a.
By design, bcrypt only accepts passwords up to 72 byte long. If you want to hash passwords with no restrictions on
their length, it is common practice to apply a cryptographic hash and then BASE64-encode For instance:
password = b"test"
b64pwd = b64encode(SHA256.new(password).digest())
bcrypt_hash = bcrypt(b64pwd, 12)
password_to_test = b"test"
try:
b64pwd = b64encode(SHA256.new(password).digest())
bcrypt_check(b64pwd, bcrypt_hash)
except ValueError:
print("Incorrect password")
Raises ValueError – if password is longer than 72 bytes or if it contains the zero byte
Crypto.Protocol.KDF.bcrypt_check(password, bcrypt_hash)
Verify if the provided password matches the given bcrypt hash.
Parameters
• password (byte string or string) – The secret password or pass phrase to
test. It must be at most 72 bytes long. It must not contain the zero byte. Unicode strings
will be encoded as UTF-8.
• bcrypt_hash (byte string, bytearray) – The reference bcrypt hash the
password needs to be checked against.
Raises ValueError – if the password does not match
HKDF
The HMAC-based Extract-and-Expand key derivation function (HKDF) was designed by Hugo Krawczyk. It is stan-
dardized in RFC 5869 and in NIST SP-800 56C.
This KDF is not suitable for deriving keys from a password or for key stretching.
Example, for deriving two AES256 keys:
salt = get_random_bytes(16)
key1, key2 = HKDF(master_secret, 32, salt, SHA512, 2)
Counter Mode
A KDF can be generically constructed with a pseudorandom function (PRF). If the PRF has a fixed-length output, you
can evaluate the PRF multiple times and concatenate the results until you collect enough derived keying material.
This function implements such type of KDF, where a counter contributes to each invokation of the PRF, as defined
in NIST SP 800-108 Rev 1. The NIST standard only allows the use of HMAC (recommended) and CMAC (not
recommended) as PRF.
This KDF is not suitable for deriving keys from a password.
Example 1 (HMAC as PRF, one AES128 key to derive):
>> from Crypto.Hash import SHA256, HMAC
>>
>> def prf(s, x):
>> return HMAC.new(s, x, SHA256).digest()
>>
>> key_derived = SP800_108_Counter(secret, 16, prf, label=b'Key A')
PBKDF1
PBKDF1 is an old key derivation function defined in version 2.0 of the PKCS#5 standard (v1.5) or in RFC2898.
Warning: Newer applications should use the more secure and versatile scrypt instead.
This module implements the Shamir’s secret sharing protocol described in the paper “How to share a secret”.
The secret can be split into an arbitrary number of shares (n), such that it is sufficient to collect just k of them to
reconstruct it (k < n). For instance, one may want to grant 16 people the ability to access a system with a pass code,
at the condition that at least 3 of them are present at the same time. As they join their shares, the pass code is revealed.
In that case, n=16 and k=3.
In the Shamir’s secret sharing scheme, the n shares are created by first defining a polynomial of degree k-1:
𝑞(𝑥) = 𝑎0 + 𝑎1 𝑥 + 𝑎2 𝑥2 + . . . + 𝑎𝑘−1 𝑥𝑘−1
The coefficient 𝑎0 is fixed with the secret value. The coefficients 𝑎1 . . . 𝑎𝑘−1 are random and they are discarded as
soon as the shares are created.
Each share is a pair (𝑥𝑖 , 𝑦𝑖 ), where 𝑥𝑖 is an arbitrary but unique number assigned to the share’s recipient and 𝑦𝑖 = 𝑞(𝑥𝑖 ).
This implementation has the following properties:
• The secret is a byte string of 16 bytes (e.g. an AES 128 key).
• Each share is a byte string of 16 bytes.
• The recipients of the shares are assigned an integer starting from 1 (share number 𝑥𝑖 ).
• The polynomial 𝑞(𝑥) is defined over the field GF(2128 ) with the same irriducible polynomial as used in AES-
GCM: 1 + 𝑥 + 𝑥2 + 𝑥7 + 𝑥128 .
• It can be compatible with the popular ssss tool when used with the 128 bit security level and no dispersion: the
command line arguments must include -s 128 -D. Note that ssss uses a slightly different polynomial:
𝑟(𝑥) = 𝑎0 + 𝑎1 𝑥 + 𝑎2 𝑥2 + . . . + 𝑎𝑘−1 𝑥𝑘−1 + 𝑥𝑘
which requires you to specify ssss=True when calling split() and combine().
Each recipient needs to hold both the share number (𝑥𝑖 , which is not confidential) and the secret (which needs to be
protected securely).
As an example, the following code shows how to protect a file meant for 5 people, in such a way that any 2 of them
are sufficient to reassemble it:
Each person can be given one share and the encrypted file.
When 2 people gather together with their shares, they can decrypt the file:
Attention: Reconstruction may succeed but still produce the incorrect secret if any of the presented shares is
incorrect (due to data corruption or to a malicious participant).
It is extremely important to also use an authentication mechanism (such as the EAX cipher mode in the example).
class Crypto.Protocol.SecretSharing.Shamir
Shamir’s secret sharing scheme.
A secret is split into n shares, and it is sufficient to collect k of them to reconstruct the secret.
static combine(shares, ssss=False)
Recombine a secret, if enough shares are presented.
Parameters
• shares (tuples) – The k tuples, each containin the index (an integer) and the share
(a byte string, 16 bytes long) that were assigned to a participant.
• ssss (bool) – If True, the shares were produced by the ssss utility. Default:
False.
Returns The original secret, as a byte string (16 bytes long).
static split(k, n, secret, ssss=False)
Split a secret into n shares.
The secret can be reconstructed later using just k shares out of the original n. Each share must be kept
confidential to the person it was assigned to.
Return (tuples): n tuples. A tuple is meant for each participant and it contains two items:
1. the unique index (an integer)
2. the share (a byte string, 16 bytes)
• Key Derivation Functions
• Secret Sharing Schemes
5.6.1 PEM
Crypto.IO.PEM.decode(pem_data, passphrase=None)
Decode a PEM block into binary.
Parameters
• pem_data (string) – The PEM block.
• passphrase (byte string) – If given and the PEM block is encrypted, the key will
be derived from the passphrase.
Returns A tuple with the binary data, the marker string, and a boolean to indicate if decryption
was performed.
Raises ValueError – if decoding fails, if the PEM file is encrypted and no passphrase has been
provided or if the passphrase is incorrect.
5.6.2 PKCS#8
PKCS#8 is a standard for storing and transferring private key information. The wrapped key can either be clear or
encrypted.
All encryption algorithms are based on passphrase-based key derivation. The following mechanisms are fully sup-
ported:
• PBKDF2WithHMAC-SHA1AndAES128-CBC
• PBKDF2WithHMAC-SHA1AndAES192-CBC
• PBKDF2WithHMAC-SHA1AndAES256-CBC
• PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC
• scryptAndAES128-CBC
• scryptAndAES192-CBC
• scryptAndAES256-CBC
The following mechanisms are only supported for importing keys. They are much weaker than the ones listed above,
and they are provided for backward compatibility only:
• pbeWithMD5AndRC2-CBC
• pbeWithMD5AndDES-CBC
• pbeWithSHA1AndRC2-CBC
• pbeWithSHA1AndDES-CBC
Crypto.IO.PKCS8.wrap(private_key, key_oid, passphrase=None, protection=None, prot_params=None,
key_params=<Crypto.Util.asn1.DerNull object>, randfunc=None)
Wrap a private key into a PKCS#8 blob (clear or encrypted).
Parameters
• private_key (byte string) – The private key encoded in binary form. The actual
encoding is algorithm specific. In most cases, it is DER.
• key_oid (string) – The object identifier (OID) of the private key to wrap. It is a
dotted string, like 1.2.840.113549.1.1.1 (for RSA keys).
• passphrase (bytes string or string) – The secret passphrase from which
the wrapping key is derived. Set it only if encryption is required.
• protection (string) – The identifier of the algorithm to use for securely wrapping
the key. The default value is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
• prot_params (dictionary) – Parameters for the protection algorithm.
Key Description
itera- The KDF algorithm is repeated several times to slow down brute force attacks
tion_count
on passwords (called N or CPU/memory cost in scrypt). The default value for
PBKDF2 is 1000. The default value for scrypt is 16384.
salt_sizeSalt is used to thwart dictionary and rainbow attacks on passwords. The de-
fault value is 8 bytes.
block_size
(scrypt only) Memory-cost (r). The default value is 8.
par- (scrypt only) CPU-cost (p). The default value is 1.
al-
leliza-
tion
Crypto.Random.random.getrandbits(N)
Return a random integer, at most N bits long.
Crypto.Random.random.randrange([start ], stop[, step ])
Return a random integer in the range (start, stop, step). By default, start is 0 and step is 1.
Crypto.Random.random.randint(a, b)
Return a random integer in the range no smaller than a and no larger than b.
Crypto.Random.random.choice(seq)
Return a random element picked from the sequence seq.
Crypto.Random.random.shuffle(seq)
Randomly shuffle the sequence seq in-place.
Crypto.Random.random.sample(population, k)
Randomly chooses k distinct elements from the list population.
This module provides minimal support for encoding and decoding ASN.1 DER objects.
class Crypto.Util.asn1.DerObject(asn1Id=None, payload=b”, implicit=None, con-
structed=False, explicit=None)
Base class for defining a single DER object.
This class should never be directly instantiated.
decode(der_encoded, strict=False)
Decode a complete DER element, and re-initializes this object with it.
Parameters der_encoded (byte string) – A complete DER element.
Raises ValueError – in case of parsing errors.
encode()
Return this DER element, fully encoded as a binary byte string.
class Crypto.Util.asn1.DerInteger(value=0, implicit=None, explicit=None)
Class to model a DER INTEGER.
An example of encoding is:
>>> s = unhexlify(b'020109')
>>> try:
>>> int_der = DerInteger()
>>> int_der.decode(s)
>>> print int_der.value
>>> except ValueError:
>>> print "Not a valid DER INTEGER"
which will show 0402aabb, the DER encoding for the byte string b'\xAA\xBB'.
For decoding:
>>> s = unhexlify(b'0402aabb')
>>> try:
>>> os_der = DerOctetString()
>>> os_der.decode(s)
>>> print hexlify(os_der.payload)
>>> except ValueError:
>>> print "Not a valid DER OCTET STRING"
which will show 3009020104020109070102, the DER encoding of the sequence containing 4, 9, and the
object with payload 02.
For decoding:
>>> s = unhexlify(b'3009020104020109070102')
>>> try:
>>> seq_der = DerSequence()
>>> seq_der.decode(s)
>>> print len(seq_der)
>>> print seq_der[0]
>>> print seq_der[:]
>>> except ValueError:
>>> print "Not a valid DER SEQUENCE"
3
4
[4, 9, b'{}']
This function returns False is the sequence is empty, or at least one member is not an integer.
Parameters only_non_negative (boolean) – If True, the presence of negative inte-
gers causes the method to return False.
class Crypto.Util.asn1.DerObjectId(value=”, implicit=None, explicit=None)
Class to model a DER OBJECT ID.
An example of encoding is:
which will show 06092a864886f70d010101, the DER encoding for the RSA Object Identifier 1.2.840.
113549.1.1.1.
For decoding:
>>> s = unhexlify(b'06092a864886f70d010101')
>>> try:
>>> oid_der = DerObjectId()
>>> oid_der.decode(s)
>>> print oid_der.value
>>> except ValueError:
>>> print "Not a valid DER OBJECT ID"
which will show 030300aabb, the DER encoding for the bit string b'\xAA\xBB'.
For decoding:
>>> s = bytes.fromhex('030300aabb')
>>> try:
>>> bs_der = DerBitString()
>>> bs_der.decode(s)
>>> print(bs_der.value.hex())
>>> except ValueError:
>>> print "Not a valid DER BIT STRING"
which will show 3109020104020105020106, the DER encoding of a SET OF with items 4,5, and 6.
For decoding:
>>> s = unhexlify(b'3109020104020105020106')
>>> try:
>>> so_der = DerSetOf()
>>> so_der.decode(s)
>>> print [x for x in so_der]
>>> except ValueError:
>>> print "Not a valid DER SET OF"
Parameters
• der_encoded (byte string) – a complete DER BIT SET OF.
• strict (boolean) – Whether decoding must check for strict DER compliancy.
Raises ValueError – in case of parsing errors.
encode()
Return this SET OF DER element, fully encoded as a binary string.
This module provides minimal support for adding and removing standard padding from data. Example:
Crypto.Util.RFC1751.english_to_key(s)
Transform a string into a corresponding key.
Example:
Parameters s (string) – the string with the words separated by whitespace; the number of
words must be a multiple of 6.
Returns A byte string.
Crypto.Util.RFC1751.key_to_english(key)
Transform an arbitrary key into a string containing English words.
Example:
Parameters key (byte string) – The key to convert. Its length must be a multiple of 8.
Returns A string of English words.
Crypto.Util.strxor.strxor_c(term, c, output=None)
From a byte string, create a second one of equal length where each byte is XOR-red with the same value.
Parameters
• term (bytes/bytearray/memoryview) – The byte string to XOR.
• c (int) – Every byte in the string will be XOR-ed with this value. It must be between 0
and 255 (included).
• output (None or bytearray/memoryview) – The location where the result
will be written to. It must have the same length as term. If None, the result is returned.
Returns If output is None, a new bytes string with the result. Otherwise None.
The counter blocks with a little endian counter will look like this:
Example of AES-CTR encryption with custom counter:
nonce = Random.get_random_bytes(4)
ctr = Counter.new(64, prefix=nonce, suffix=b'ABCD', little_endian=True, initial_
˓→value=10)
Crypto.Util.number.bytes_to_long(s)
Convert a byte string to a long integer (big endian).
In Python 3.2+, use the native method instead:
For instance:
>>> int.from_bytes(b'P', 'big')
80
This is (essentially) the inverse of long_to_bytes().
Crypto.Util.number.ceil_div(n, d)
Return ceil(n/d), that is, the smallest integer r such that r*d >= n
Crypto.Util.number.getPrime(N, randfunc=None)
Return a random N-bit prime number.
N must be an integer larger than 1. If randfunc is omitted, then Random.get_random_bytes() is used.
Crypto.Util.number.getRandomInteger(N, randfunc=None)
Return a random number at most N bits long.
If randfunc is omitted, then Random.get_random_bytes() is used.
Deprecated since version 3.0: This function is for internal use only and may be renamed or removed in the
future. Use Crypto.Random.random.getrandbits() instead.
Crypto.Util.number.getRandomNBitInteger(N, randfunc=None)
Return a random number with exactly N-bits, i.e. a random number between 2**(N-1) and (2**N)-1.
If randfunc is omitted, then Random.get_random_bytes() is used.
Deprecated since version 3.0: This function is for internal use only and may be renamed or removed in the
future.
Crypto.Util.number.getRandomRange(a, b, randfunc=None)
Return a random number n so that a <= n < b.
If randfunc is omitted, then Random.get_random_bytes() is used.
Deprecated since version 3.0: This function is for internal use only and may be renamed or removed in the
future. Use Crypto.Random.random.randrange() instead.
Crypto.Util.number.getStrongPrime(N, e=0, false_positive_prob=1e-06, randfunc=None)
Return a random strong N-bit prime number. In this context, p is a strong prime if p-1 and p+1 have at least one
large prime factor.
Parameters
• N (integer) – the exact length of the strong prime. It must be a multiple of 128 and >
512.
• e (integer) – if provided, the returned prime (minus 1) will be coprime to e and thus
suitable for RSA where e is the public exponent.
• false_positive_prob (float) – The statistical probability for the result not to be
actually a prime. It defaults to 10-6 . Note that the real probability of a false-positive is far
less. This is just the mathematically provable limit.
Note: In Python 3, if you are sure that n can fit into blocksize bytes, you can simply use the native method
instead:
For instance:
>>> n = 80
>>> n.to_bytes(2, 'big')
b'\x00P'
However, and unlike this long_to_bytes() function, an OverflowError exception is raised if n does
not fit.
Crypto.Util.number.size(N)
Returns the size of the number N in bits.
All cryptographic functionalities are organized in sub-packages; each sub-package is dedicated to solving a specific
class of problems.
Package Description
Crypto.Cipher Modules for protecting confidentiality that is, for encrypting and decrypting data (example:
AES).
Crypto.Signature Modules for assuring authenticity, that is, for creating and verifying digital signatures of
messages (example: PKCS#1 v1.5).
Crypto.Hash Modules for creating cryptographic digests (example: SHA-256).
Crypto.PublicKey Modules for generating, exporting or importing public keys (example: RSA or ECC).
Crypto.Protocol Modules for faciliting secure communications between parties, in most cases by leveraging
cryptograpic primitives from other modules (example: Shamir’s Secret Sharing scheme).
Crypto.IO Modules for dealing with encodings commonly used for cryptographic data (example:
PEM).
Crypto.Random Modules for generating random data.
Crypto.Util General purpose routines (example: XOR for byte strings).
In certain cases, there is some overlap between these categories. For instance, authenticity is also provided by
Message Authentication Codes, and some can be built using digests, so they are included in the Crypto.Hash
package (example: HMAC). Also, cryptographers have over time realized that encryption without authentication is
often of limited value so recent ciphers found in the Crypto.Cipher package embed it (example: GCM).
PyCryptodome strives to maintain strong backward compatibility with the old PyCrypto’s API (except for those few
cases where that is harmful to security) so a few modules don’t appear where they should (example: the ASN.1 module
is under Crypto.Util as opposed to Crypto.IO).
Examples
The following code generates a new AES128 key and encrypts a piece of data into a file. We use the EAX mode because
it allows the receiver to detect any unauthorized modification (similarly, we could have used other authenticated
encryption modes like GCM, CCM or SIV).
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
At the other end, the receiver can securely load the piece of data back (if they know the key!). Note that the code
generates a ValueError exception when tampering is detected.
79
PyCryptodome Documentation, Release 3.17.0
The following code generates a new RSA key pair (secret) and saves it into a file, protected by a password. We use
the scrypt key derivation function to thwart dictionary attacks. At the end, the code prints our the RSA public key in
ASCII/PEM format:
secret_code = "Unguessable"
key = RSA.generate(2048)
encrypted_key = key.export_key(passphrase=secret_code, pkcs=8,
protection="scryptAndAES128-CBC")
print(key.publickey().export_key())
The following code reads the private RSA key back in, and then prints again the public key:
secret_code = "Unguessable"
encoded_key = open("rsa_key.bin", "rb").read()
key = RSA.import_key(encoded_key, passphrase=secret_code)
print(key.publickey().export_key())
The following code generates public key stored in receiver.pem and private key stored in private.pem. These
files will be used in the examples below. Every time, it generates different public key and private key pair.
key = RSA.generate(2048)
private_key = key.export_key()
file_out = open("private.pem", "wb")
file_out.write(private_key)
file_out.close()
public_key = key.publickey().export_key()
file_out = open("receiver.pem", "wb")
file_out.write(public_key)
file_out.close()
The following code encrypts a piece of data for a receiver we have the RSA public key of. The RSA public key is
stored in a file called receiver.pem.
80 Chapter 6. Examples
PyCryptodome Documentation, Release 3.17.0
Since we want to be able to encrypt an arbitrary amount of data, we use a hybrid encryption scheme. We use RSA
with PKCS#1 OAEP for asymmetric encryption of an AES session key. The session key can then be used to encrypt
all the actual data.
As in the first example, we use the EAX mode to allow detection of unauthorized modifications.
recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)
The receiver has the private RSA key. They will use it to decrypt the session key first, and with that the rest of the file:
private_key = RSA.import_key(open("private.pem").read())
82 Chapter 6. Examples
CHAPTER 7
You are effectively using CTR mode without a fixed nonce and with a 128-bit big endian counter starting at 0. The
counter will wrap around only after 2128 blocks.
You can replicate the same keystream in PyCryptodome with:
ivSpec = b'\x00' * 16
ctr = AES.new(keySpec, AES.MODE_CTR, initial_value=ivSpec, nonce=b'')
Yes. For Java, you must consider that by default the mask is generated by MGF1 with SHA-1 (regardless of how you
hash the message) and the salt is 20 bytes long.
If you want to use another algorithm or another salt length, you must instantiate a PSSParameterSpec object, for
instance:
Signature ss = Signature.getInstance("SHA256withRSA/PSS");
AlgorithmParameters pss1 = ss.getParameters();
(continues on next page)
83
PyCryptodome Documentation, Release 3.17.0
ss.setParameter(spec1);
Yes, but one quirk of OpenSSL (and of a few other libraries, especially if they are wrappers to OpenSSL) is that the
salt length is computed in two possible ways:
In PyCryptodome, the salt length matches the digest size by default (which is what RFC8017 recommends). However,
you can also maximize the salt length with:
key = RSA.import_key(open('privkey.der').read())
h = SHA256.new(message)
max_salt_bytes = key.size_in_bytes() - h.digest_size - 2
signature = pss.new(key, salt_bytes=max_salt_bytes).sign(h)
You might find a directory named crypto, with all the PyCryptodome files in it.
The most likely cause is described here and you can fix the problem with:
pip uninstall crypto
pip uninstall pycryptodome
pip install pycryptodome
The root cause is that, in the past, you most likely have installed an unrelated but similarly named package called
crypto, which happens to operate under the namespace crypto.
The Windows filesystem is case-insensitive so crypto and Crypto are effectively considered the same thing. When
you subsequently install pycryptodome, pip finds that a directory named with the target namespace already exists
(under the rules of the underlying filesystem), and therefore installs all the sub-packages of pycryptodome in it.
This is probably a reasonable behavior, if it wasn’t that pip does not issue any warning even if it could detect the issue.
Most probably you have installed both the pycryptodome and the old pycrypto packages.
Unfortunately,‘‘pycparser‘‘ does not work with optimzed (-O) Python builds, which strips out the docstrings, causing
this error. This is a known issue and it will not be fixed.
The possible workarounds are:
• Do not run Python iwth -O
• Remove cffi and cparser. PyCryptodome will fall back to ctypes for interfacing with the native modules.
• Use an earlier version of cparser (2.14)
• Do not be afraid to contribute with small and apparently insignificant improvements like correction to typos.
Every change counts.
• Read carefully the License of PyCryptodome. By submitting your code, you acknowledge that you accept to
release it according to the BSD 2-clause license.
• You must disclaim which parts of your code in your contribution were partially copied or derived from an
existing source. Ensure that the original is licensed in a way compatible to the BSD 2-clause license.
• You can propose changes in any way you find most convenient. However, the preferred approach is to:
– Clone the main repository on GitHub.
– Create a branch and modify the code.
– Send a pull request upstream with a meaningful description.
• Provide tests (in Crypto.SelfTest) along with code. If you fix a bug add a test that fails in the current
version and passes with your change.
• If your change breaks backward compatibility, highlight it and include a justification.
• Ensure that your code complies to PEP8 and PEP257.
• If you add or modify a public interface, make sure the relevant type stubs remain up to date.
• Ensure that your code does not use constructs or includes modules not present in Python 2.6.
• Add a short summary of the change to the file Changelog.rst.
• Add your name to the list of contributors in the file AUTHORS.rst.
The PyCryptodome mailing list is hosted on Google Groups. You can mail any comment or question to py-
[email protected].
Bug reports can be filed on the GitHub tracker.
87
PyCryptodome Documentation, Release 3.17.0
Future plans
89
PyCryptodome Documentation, Release 3.17.0
Changelog
• Added support for the Counter Mode KDF defined in SP 800-108 Rev 1.
• Reduce the minimum tag length for the EAX cipher to 2 bytes.
• An RSA object has 4 new properties for the CRT coefficients: dp, dq, invq and invq (invp is the same
value as the existing u).
91
PyCryptodome Documentation, Release 3.17.0
• Build PyPy wheels only for versions 3.8 and 3.9, and not for 3.7 anymore.
• Add support for curves Ed25519 and Ed448, including export and import of keys.
• Add support for EdDSA signatures.
• Add support for Asymmetric Key Packages (RFC5958) to import private keys.
• GH#620: for Crypto.Util.number.getPrime , do not sequentially scan numbers searching for a prime.
• GH#595: Fixed memory leak for GMP integers. Thanks to Witalij Siebert and Pablo Quílez.
• Relaxed ECDSA requirements for FIPS 186 signatures and accept any SHA-2 or SHA-3 hash. sign() and
verify() will be performed even if the hash is stronger than the ECC key.
• GH#512: Especially for very small bit sizes, Crypto.Util.number.getPrime() was occasionally gen-
erating primes larger than given the bit size. Thanks to Koki Takahashi.
• GH#552: Correct typing annotations for PKCS115_Cipher.decrypt().
• GH#555: decrypt() method of a PKCS#1v1.5 cipher returned a bytearray instead of bytes.
• GH#557: External DSA domain parameters were accepted even when the modulus (p) was not prime. This
affected Crypto.PublicKey.DSA.generate() and Crypto.PublicKey.DSA.construct().
Thanks to Koki Takahashi.
• Added cSHAKE128 and cSHAKE256 (of SHA-3 family). Thanks to Michael Schaffner.
• GH#558: The flag RTLD_DEEPBIND passed to dlopen() is not well supported by address sanitizers. It
is now possible to set the environment variable PYCRYPTDOME_DISABLE_DEEPBIND to drop that flag and
allow security testing.
• The Windows wheels of Python 2.7 now require the VS2015 runtime to be installed in the system, because
Microsoft stopped distributing the VS2008 compiler in April 2021. VS2008 was used to compile the Python 2.7
extensions.
• The bulk of the test vectors have been moved to the separate package pycryptodome-test-vectors. As
result, packages pycryptodome and pycryptodomex become significantly smaller (from 14MB to 3MB).
• Moved CI tests and build service from Travis CI to GitHub Actions.
• GH#426: The Shamir’s secret sharing implementation is not actually compatible with ssss. Added an optional
parameter to enable interoperability.
• GH#381: Make notarization possible again on OS X when using wheels. Thanks to Colin Atkinson.
• RSA OAEP decryption was not verifying that all PS bytes are zero.
• GH#372: fixed memory leak for operations that use memoryviews when cffi is not installed.
• Fixed wrong ASN.1 OID for HMAC-SHA512 in PBE2.
• GH#341: Prevent key_to_english from creating invalid data when fed with keys of length not multiple of
8. Thanks to vstoykovbg.
• GH#347: Fix blocking RSA signing/decryption when key has very small factor. Thanks to Martijn Pieters.
• GH#308: Align stack of functions using SSE2 intrinsics to avoid crashes, when compiled with gcc on 32-bit
x86 platforms.
• GH#308: Avoid allocating arrays of __m128i on the stack, to cope with buggy compilers.
• GH#322: Remove blanket -O3 optimization for gcc and clang, to cope with buggy compilers.
• GH#337: Fix typing stubs for signatures.
• GH#338: Deal with gcc installations that don’t have x86intrin.h.
• Add support for loading PEM files encrypted with AES192-CBC and AES256-GCM.
• When importing ECC keys in PEM format, ignore the redundant EC PARAMS section that was included by
certain openssl commands.
• Speed-up ECC performance. ECDSA is 33 times faster on the NIST P-256 curve.
• Added support for NIST P-384 and P-521 curves.
• EccKey has new methods size_in_bits() and size_in_bytes().
• Support HMAC-SHA224, HMAC-SHA256, HMAC-SHA384, and HMAC-SHA512 in PBE2/PBKDF2.
• DER objects were not rejected if their length field had a leading zero.
• Allow legacy RC2 ciphers to have 40-bit keys.
• ASN.1 Object IDs did not allow the value 0 in the path.
• GH#258: False positive on PSS signatures when externally provided salt is too long.
• Include type stub files for Crypto.IO and Crypto.Util.
• Added type stubs to enable static type checking with mypy. Thanks to Michael Nix.
• New update_after_digest flag for CMAC.
• Added support for Poly1305 MAC (with AES and ChaCha20 ciphers for key derivation).
• Added support for ChaCha20-Poly1305 AEAD cipher.
• New parameter output for Crypto.Util.strxor.strxor, Crypto.Util.strxor.strxor_c,
encrypt and decrypt methods in symmetric ciphers (Crypto.Cipher package). output is a pre-
allocated buffer (a bytearray or a writeable memoryview) where the result must be stored. This requires
less memory for very large payloads; it is also more efficient when encrypting (or decrypting) several small
payloads.
• GH#266: AES-GCM hangs when processing more than 4GB at a time on x86 with PCLMULQDQ instruction.
• GH#198: Fix vulnerability on AESNI ECB with payloads smaller than 16 bytes (CVE-2018-15560).
• GH#187: Fixed incorrect AES encryption/decryption with AES acceleration on x86 due to gcc’s optimization
and strict aliasing rules.
• GH#188: More prime number candidates than necessary where discarded as composite due to the limited way
D values were searched in the Lucas test.
• Fixed ResouceWarnings and DeprecationWarnings.
• Workaround for Python 3.7.0 bug on Windows (https://bugs.python.org/issue34108).
• GH#175: Fixed incorrect results for CTR encryption/decryption with more than 8 blocks.
• ChaCha20 accepts 96 bit nonces (in addition to 64 bit nonces) as defined in RFC7539.
• Accelerate AES-GCM on x86 using PCLMULQDQ instruction.
• Accelerate AES-ECB and AES-CTR on x86 by pipelining AESNI instructions.
• As result of the two improvements above, on x86 (Broadwell):
– AES-ECB and AES-CTR are 3x faster
– AES-GCM is 9x faster
• In Crypto.Util.number, functions floor_div and exact_div have been removed. Also, ceil_div
is limited to non-negative terms only.
• Added Google Wycheproof tests (https://github.com/google/wycheproof) for RSA, DSA, ECDSA, GCM, SIV,
EAX, CMAC.
• New parameter mac_len (length of MAC tag) for CMAC.
• In certain circumstances (at counter wrapping, which happens on average after 32 GB) AES GCM produced
wrong ciphertexts.
• Method encrypt() of AES SIV cipher could be still called, whereas only encrypt_and_digest() is
allowed.
• Introduced export_key and deprecated exportKey for DSA and RSA key objects.
• Ciphers and hash functions accept memoryview objects in input.
• Added support for SHA-512/224 and SHA-512/256.
• Without libgmp, modular exponentiation (since v3.4.8) crashed on 32-bit big-endian systems.
• GH#121. the record list was still not correct due to PEP3147 and __pycache__ directories. Thanks again to
John O’Brien.
• When creating ElGamal keys, the generator wasn’t a square residue: ElGamal encryption done with those keys
cannot be secure under the DDH assumption. Thanks to Weikeng Chen.
• GH#123 and #125. The SSE2 command line switch was not always passed on 32-bit x86 platforms.
• GH#121. The record list (–record) was not always correctly filled for the pycryptodomex package. Thanks to
John W. O’Brien.
• Added a native extension in pure C for modular exponentiation, optimized for SSE2 on x86. In the process, we
drop support for the arbitrary arithmetic library MPIR on Windows, which is painful to compile and deploy. The
custom modular exponentiation is 130% (160%) slower on an Intel CPU in 32-bit (64-bit) mode, compared to
MPIR. Still, that is much faster that CPython’s own pow() function which is 900% (855%) slower than MPIR.
Support for the GMP library on Unix remains.
• Added support for manylinux wheels.
• Support for Python 3.7.
• The DSA parameter ‘p’ prime was created with 255 bits cleared (but still with the correct strength).
• GH#106. Not all docs were included in the tar ball. Thanks to Christopher Hoskin.
• GH#109. ECDSA verification failed for DER encoded signatures. Thanks to Alastair Houghton.
• Human-friendly messages for padding errors with ECB and CBC.
• GH#65. Keccak, SHA3, SHAKE and the seek functionality for ChaCha20 were not working on big endian
machines. Fixed. Thanks to Mike Gilbert.
• A few fixes in the documentation.
• Added option to install the library under the Cryptodome package (instead of Crypto).
• Added Crypto.PublicKey.ECC module (NIST P-256 curve only), including export/import of ECC keys.
• Added support for ECDSA (FIPS 186-3 and RFC6979).
• RSA key size is now returned correctly in RsaKey.__repr__() method (kudos to hannesv).
• CTR mode does not modify anymore counter parameter passed to new() method.
• CTR raises OverflowError instead of ValueError when the counter wraps around.
• PEM files with Windows newlines could not be imported.
• Crypto.IO.PEM and Crypto.IO.PKCS8 used to accept empty passphrases.
• GH#6: NotImplementedError now raised for unsupported methods sign, verify, encrypt, decrypt,
blind, unblind and size in objects RsaKey, DsaKey, ElGamalKey.
• Opt-in for update() after digest() for SHA-3, keccak, BLAKE2 hashes
• Removed unused SHA-3 and keccak test vectors, therefore significantly reducing the package from 13MB to
3MB.
• Removed keyword verify_x509_cert from module method importKey (RSA and DSA).
• Reverted to original PyCrypto behavior of method verify in PKCS1_v1_5 and PKCS1_PSS.
• Speed up execution of Public Key algorithms on PyPy, when backed by the Gnu Multiprecision (GMP) library.
• GMP headers and static libraries are not required anymore at the time PyCryptodome is built. Instead, the code
will automatically use the GMP dynamic library (.so/.DLL) if found in the system at runtime.
• Reduced the amount of C code by almost 40% (4700 lines). Modularized and simplified all code (C and Python)
related to block ciphers. Pycryptodome is now free of CPython extensions.
• Add support for CI in Windows via Appveyor.
• RSA and DSA key generation more closely follows FIPS 186-4 (though it is not 100% compliant).
• None
• Crypto.Random stops being a userspace CSPRNG. It is now a pure wrapper over os.urandom.
• Added certain resistance against side-channel attacks for GHASH (GCM) and DSA.
• More test vectors for HMAC-RIPEMD-160.
• Update libtomcrypt headers and code to v1.17 (kudos to Richard Mitchell).
• RSA and DSA keys are checked for consistency as they are imported.
• Simplified build process by removing autoconf.
• Speed optimization to PBKDF2.
• Add support for MSVC.
• Replaced HMAC code with a BSD implementation. Clarified that starting from the fork, all contributions are
released under the BSD license.
License
The source code in PyCryptodome is partially in the public domain and partially released under the BSD 2-Clause
license.
In either case, there are minimal if no restrictions on the redistribution, modification and usage of the software.
All code originating from PyCrypto is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as
a compiled binary, for any purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright
interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the
detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of
all present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PAR-
TICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
All direct contributions to PyCryptodome are released under the following license. The copyright of each piece belongs
to the respective author.
111
PyCryptodome Documentation, Release 3.17.0
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the follow-
ing disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, IN-
CIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSI-
NESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CON-
TRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAM-
AGE.
c
Crypto.IO.PEM, 63
Crypto.IO.PKCS8, 64
Crypto.Protocol.SecretSharing, 62
Crypto.PublicKey.DSA, 45
Crypto.PublicKey.ECC, 49
Crypto.PublicKey.ElGamal, 54
Crypto.PublicKey.RSA, 40
Crypto.Util.asn1, 66
Crypto.Util.Counter, 74
Crypto.Util.number, 75
Crypto.Util.Padding, 71
Crypto.Util.RFC1751, 72
Crypto.Util.strxor, 72
113
PyCryptodome Documentation, Release 3.17.0
A Crypto.Random.random.shuffle() (built-in
add() (Crypto.Util.asn1.DerSetOf method), 70 function), 66
Crypto.Util.asn1 (module), 66
B Crypto.Util.Counter (module), 74
Crypto.Util.number (module), 75
bcrypt() (in module Crypto.Protocol.KDF), 58
Crypto.Util.Padding (module), 71
bcrypt_check() (in module Crypto.Protocol.KDF),
Crypto.Util.RFC1751 (module), 72
58
Crypto.Util.strxor (module), 72
bytes_to_long() (in module Crypto.Util.number),
75
D
C decode() (Crypto.Util.asn1.DerBitString method), 70
ceil_div() (in module Crypto.Util.number), 75 decode() (Crypto.Util.asn1.DerInteger method), 67
combine() (Crypto.Protocol.SecretSharing.Shamir decode() (Crypto.Util.asn1.DerObject method), 66
static method), 62 decode() (Crypto.Util.asn1.DerObjectId method), 69
construct() (in module Crypto.PublicKey.DSA), 46 decode() (Crypto.Util.asn1.DerSequence method), 68
construct() (in module Crypto.PublicKey.ECC), 51 decode() (Crypto.Util.asn1.DerSetOf method), 70
construct() (in module Crypto.PublicKey.ElGamal), decode() (in module Crypto.IO.PEM), 63
54 decrypt_and_verify(), 25
construct() (in module Crypto.PublicKey.RSA), 41 DerBitString (class in Crypto.Util.asn1), 69
copy() (Crypto.PublicKey.ECC.EccPoint method), 51 DerInteger (class in Crypto.Util.asn1), 66
Crypto.IO.PEM (module), 63 DerNull (class in Crypto.Util.asn1), 67
Crypto.IO.PKCS8 (module), 64 DerObject (class in Crypto.Util.asn1), 66
Crypto.Protocol.SecretSharing (module), 62 DerObjectId (class in Crypto.Util.asn1), 69
Crypto.PublicKey.DSA (module), 45 DerOctetString (class in Crypto.Util.asn1), 67
Crypto.PublicKey.ECC (module), 49 DerSequence (class in Crypto.Util.asn1), 67
Crypto.PublicKey.ElGamal (module), 54 DerSetOf (class in Crypto.Util.asn1), 70
Crypto.PublicKey.RSA (module), 40 digest(), 23
Crypto.Random.get_random_bytes() (built-in domain() (Crypto.PublicKey.DSA.DsaKey method), 46
function), 65 double() (Crypto.PublicKey.ECC.EccPoint method),
Crypto.Random.random.choice() (built-in 51
function), 66 DsaKey (class in Crypto.PublicKey.DSA), 46
Crypto.Random.random.getrandbits()
(built-in function), 66 E
Crypto.Random.random.randint() (built-in EccKey (class in Crypto.PublicKey.ECC), 49
function), 66 EccPoint (class in Crypto.PublicKey.ECC), 51
Crypto.Random.random.randrange() (built-in ElGamalKey (class in Crypto.PublicKey.ElGamal), 55
function), 66 encode() (Crypto.Util.asn1.DerBitString method), 70
Crypto.Random.random.sample() (built-in encode() (Crypto.Util.asn1.DerInteger method), 67
function), 66 encode() (Crypto.Util.asn1.DerObject method), 66
115
PyCryptodome Documentation, Release 3.17.0
116 Index
PyCryptodome Documentation, Release 3.17.0
size_in_bytes() (Crypto.PublicKey.ECC.EccPoint
method), 51
size_in_bytes() (Crypto.PublicKey.RSA.RsaKey
method), 44
SP800_108_Counter() (in module
Crypto.Protocol.KDF), 60
split() (Crypto.Protocol.SecretSharing.Shamir static
method), 62
strxor() (in module Crypto.Util.strxor), 72
strxor_c() (in module Crypto.Util.strxor), 72
U
unpad() (in module Crypto.Util.Padding), 71
UnsupportedEccFeature, 51
unwrap() (in module Crypto.IO.PKCS8), 65
update(), 23
V
verify(), 24
W
wrap() (in module Crypto.IO.PKCS8), 64
Index 117