Upgrade cryptography from 2.5 to 3.3
Source code is from https://github.com/pyca/cryptography/tree/3.3.x
Run setup.py locally and rename _openssl.so/_padding.so
Bug: 205265538
Test: None
Change-Id: If031739ef5830ba2fb177add74515e4660e2906e
diff --git a/tests/hazmat/primitives/fixtures_dh.py b/tests/hazmat/primitives/fixtures_dh.py
new file mode 100644
index 0000000..b766c42
--- /dev/null
+++ b/tests/hazmat/primitives/fixtures_dh.py
@@ -0,0 +1,26 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from __future__ import absolute_import, division, print_function
+
+from cryptography.hazmat.primitives.asymmetric import dh
+
+FFDH3072_P = dh.DHParameterNumbers(
+ p=int(
+ "ffffffffffffffffadf85458a2bb4a9aafdc5620273d3cf1d8b9c583ce2d3695a9e"
+ "13641146433fbcc939dce249b3ef97d2fe363630c75d8f681b202aec4617ad3df1e"
+ "d5d5fd65612433f51f5f066ed0856365553ded1af3b557135e7f57c935984f0c70e"
+ "0e68b77e2a689daf3efe8721df158a136ade73530acca4f483a797abc0ab182b324"
+ "fb61d108a94bb2c8e3fbb96adab760d7f4681d4f42a3de394df4ae56ede76372bb1"
+ "90b07a7c8ee0a6d709e02fce1cdf7e2ecc03404cd28342f619172fe9ce98583ff8e"
+ "4f1232eef28183c3fe3b1b4c6fad733bb5fcbc2ec22005c58ef1837d1683b2c6f34"
+ "a26c1b2effa886b4238611fcfdcde355b3b6519035bbc34f4def99c023861b46fc9"
+ "d6e6c9077ad91d2691f7f7ee598cb0fac186d91caefe130985139270b4130c93bc4"
+ "37944f4fd4452e2d74dd364f2e21e71f54bff5cae82ab9c9df69ee86d2bc522363a"
+ "0dabc521979b0deada1dbf9a42d5c4484e0abcd06bfa53ddef3c1b20ee3fd59d7c2"
+ "5e41d2b66c62e37ffffffffffffffff",
+ 16,
+ ),
+ g=2,
+)
diff --git a/tests/hazmat/primitives/fixtures_dsa.py b/tests/hazmat/primitives/fixtures_dsa.py
index dd947ae..d4568ea 100644
--- a/tests/hazmat/primitives/fixtures_dsa.py
+++ b/tests/hazmat/primitives/fixtures_dsa.py
@@ -5,7 +5,9 @@
from __future__ import absolute_import, division, print_function
from cryptography.hazmat.primitives.asymmetric.dsa import (
- DSAParameterNumbers, DSAPrivateNumbers, DSAPublicNumbers
+ DSAParameterNumbers,
+ DSAPrivateNumbers,
+ DSAPublicNumbers,
)
@@ -13,140 +15,147 @@
public_numbers=DSAPublicNumbers(
parameter_numbers=DSAParameterNumbers(
p=int(
- 'd38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725ef34'
- '1eabb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae7912102b6'
- 'b502e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189cef'
- '1ace778d7845a5c1c1c7147123188f8dc551054ee162b634d60f097f7'
- '19076640e20980a0093113a8bd73', 16
+ "d38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725ef34"
+ "1eabb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae7912102b6"
+ "b502e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189cef"
+ "1ace778d7845a5c1c1c7147123188f8dc551054ee162b634d60f097f7"
+ "19076640e20980a0093113a8bd73",
+ 16,
),
- q=int('96c5390a8b612c0e422bb2b0ea194a3ec935a281', 16),
+ q=int("96c5390a8b612c0e422bb2b0ea194a3ec935a281", 16),
g=int(
- '06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce499'
- '1d2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d30'
- '0042bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34c'
- 'd12615474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f4'
- 'fd9f93cd6f4f17fc076341a7e7d9', 16
- )
+ "06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce499"
+ "1d2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d30"
+ "0042bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34c"
+ "d12615474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f4"
+ "fd9f93cd6f4f17fc076341a7e7d9",
+ 16,
+ ),
),
y=int(
- '6f26d98d41de7d871b6381851c9d91fa03942092ab6097e76422070edb71d'
- 'b44ff568280fdb1709f8fc3feab39f1f824adaeb2a298088156ac31af1aa0'
- '4bf54f475bdcfdcf2f8a2dd973e922d83e76f016558617603129b21c70bf7'
- 'd0e5dc9e68fe332e295b65876eb9a12fe6fca9f1a1ce80204646bf99b5771'
- 'd249a6fea627', 16
- )
+ "6f26d98d41de7d871b6381851c9d91fa03942092ab6097e76422070edb71d"
+ "b44ff568280fdb1709f8fc3feab39f1f824adaeb2a298088156ac31af1aa0"
+ "4bf54f475bdcfdcf2f8a2dd973e922d83e76f016558617603129b21c70bf7"
+ "d0e5dc9e68fe332e295b65876eb9a12fe6fca9f1a1ce80204646bf99b5771"
+ "d249a6fea627",
+ 16,
+ ),
),
- x=int('8185fee9cc7c0e91fd85503274f1cd5a3fd15a49', 16)
+ x=int("8185fee9cc7c0e91fd85503274f1cd5a3fd15a49", 16),
)
DSA_KEY_2048 = DSAPrivateNumbers(
public_numbers=DSAPublicNumbers(
parameter_numbers=DSAParameterNumbers(
p=int(
- 'ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace5e9c4'
- '1434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17dac62c98e70'
- '6af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b12252c40278fff'
- '9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d244e54561b0'
- 'dca39b301de8c49da9fb23df33c6182e3f983208c560fb5119fbf78eb'
- 'e3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a2b4f0e9e3'
- 'd9dbac122f750dd754325135257488b1f6ecabf21bff2947fe0d3b2cb'
- '7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a908c36e9'
- '5e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac5aa66ef7',
- 16
+ "ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace5e9c4"
+ "1434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17dac62c98e70"
+ "6af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b12252c40278fff"
+ "9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d244e54561b0"
+ "dca39b301de8c49da9fb23df33c6182e3f983208c560fb5119fbf78eb"
+ "e3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a2b4f0e9e3"
+ "d9dbac122f750dd754325135257488b1f6ecabf21bff2947fe0d3b2cb"
+ "7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a908c36e9"
+ "5e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac5aa66ef7",
+ 16,
),
q=int(
- '8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b18f507'
- '192c19d', 16
+ "8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b18f507"
+ "192c19d",
+ 16,
),
g=int(
- 'e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b1'
- '913413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9'
- '8076739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908b'
- 'ae03e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d555'
- '1b2fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c6156'
- '8f78d0706b10a26f23b4f197c322b825002284a0aca91807bba98ece9'
- '12b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f840387'
- '3d12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed27'
- '3b146ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302',
- 16
- )
+ "e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b1"
+ "913413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9"
+ "8076739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908b"
+ "ae03e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d555"
+ "1b2fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c6156"
+ "8f78d0706b10a26f23b4f197c322b825002284a0aca91807bba98ece9"
+ "12b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f840387"
+ "3d12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed27"
+ "3b146ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302",
+ 16,
+ ),
),
y=int(
- '6b32e31ab9031dc4dd0b5039a78d07826687ab087ae6de4736f5b0434e125'
- '3092e8a0b231f9c87f3fc8a4cb5634eb194bf1b638b7a7889620ce6711567'
- 'e36aa36cda4604cfaa601a45918371d4ccf68d8b10a50a0460eb1dc0fff62'
- 'ef5e6ee4d473e18ea4a66c196fb7e677a49b48241a0b4a97128eff30fa437'
- '050501a584f8771e7280d26d5af30784039159c11ebfea10b692fd0a58215'
- 'eeb18bff117e13f08db792ed4151a218e4bed8dddfb0793225bd1e9773505'
- '166f4bd8cedbb286ea28232972da7bae836ba97329ba6b0a36508e50a52a7'
- '675e476d4d4137eae13f22a9d2fefde708ba8f34bf336c6e76331761e4b06'
- '17633fe7ec3f23672fb19d27', 16
- )
+ "6b32e31ab9031dc4dd0b5039a78d07826687ab087ae6de4736f5b0434e125"
+ "3092e8a0b231f9c87f3fc8a4cb5634eb194bf1b638b7a7889620ce6711567"
+ "e36aa36cda4604cfaa601a45918371d4ccf68d8b10a50a0460eb1dc0fff62"
+ "ef5e6ee4d473e18ea4a66c196fb7e677a49b48241a0b4a97128eff30fa437"
+ "050501a584f8771e7280d26d5af30784039159c11ebfea10b692fd0a58215"
+ "eeb18bff117e13f08db792ed4151a218e4bed8dddfb0793225bd1e9773505"
+ "166f4bd8cedbb286ea28232972da7bae836ba97329ba6b0a36508e50a52a7"
+ "675e476d4d4137eae13f22a9d2fefde708ba8f34bf336c6e76331761e4b06"
+ "17633fe7ec3f23672fb19d27",
+ 16,
+ ),
),
x=int(
- '405772da6e90d809e77d5de796562a2dd4dfd10ef00a83a3aba6bd818a0348a1',
- 16
- )
+ "405772da6e90d809e77d5de796562a2dd4dfd10ef00a83a3aba6bd818a0348a1", 16
+ ),
)
DSA_KEY_3072 = DSAPrivateNumbers(
public_numbers=DSAPublicNumbers(
parameter_numbers=DSAParameterNumbers(
p=int(
- 'f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d582'
- '8c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a84'
- '2ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e'
- '80abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84e'
- 'c389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea265'
- '1b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a142'
- '85a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab060'
- '548de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba'
- '9844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1'
- 'd54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818'
- 'f06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673'
- 'ae4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f747'
- '6cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c1'
- '136f303f4b4d25ad5b692229957', 16
+ "f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d582"
+ "8c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a84"
+ "2ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e"
+ "80abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84e"
+ "c389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea265"
+ "1b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a142"
+ "85a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab060"
+ "548de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba"
+ "9844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1"
+ "d54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818"
+ "f06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673"
+ "ae4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f747"
+ "6cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c1"
+ "136f303f4b4d25ad5b692229957",
+ 16,
),
q=int(
- 'd3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210f6169'
- '041653b', 16
+ "d3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210f6169"
+ "041653b",
+ 16,
),
g=int(
- 'ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978db2104'
- 'd7394b493c18332c64cec906a71c3778bd93341165dee8e6cd4ca6f13'
- 'afff531191194ada55ecf01ff94d6cf7c4768b82dd29cd131aaf202ae'
- 'fd40e564375285c01f3220af4d70b96f1395420d778228f1461f5d0b8'
- 'e47357e87b1fe3286223b553e3fc9928f16ae3067ded6721bedf1d1a0'
- '1bfd22b9ae85fce77820d88cdf50a6bde20668ad77a707d1c60fcc5d5'
- '1c9de488610d0285eb8ff721ff141f93a9fb23c1d1f7654c07c46e588'
- '36d1652828f71057b8aff0b0778ef2ca934ea9d0f37daddade2d823a4'
- 'd8e362721082e279d003b575ee59fd050d105dfd71cd63154efe431a0'
- '869178d9811f4f231dc5dcf3b0ec0f2b0f9896c32ec6c7ee7d60aa971'
- '09e09224907328d4e6acd10117e45774406c4c947da8020649c3168f6'
- '90e0bd6e91ac67074d1d436b58ae374523deaf6c93c1e6920db4a080b'
- '744804bb073cecfe83fa9398cf150afa286dc7eb7949750cf5001ce10'
- '4e9187f7e16859afa8fd0d775ae', 16
- )
+ "ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978db2104"
+ "d7394b493c18332c64cec906a71c3778bd93341165dee8e6cd4ca6f13"
+ "afff531191194ada55ecf01ff94d6cf7c4768b82dd29cd131aaf202ae"
+ "fd40e564375285c01f3220af4d70b96f1395420d778228f1461f5d0b8"
+ "e47357e87b1fe3286223b553e3fc9928f16ae3067ded6721bedf1d1a0"
+ "1bfd22b9ae85fce77820d88cdf50a6bde20668ad77a707d1c60fcc5d5"
+ "1c9de488610d0285eb8ff721ff141f93a9fb23c1d1f7654c07c46e588"
+ "36d1652828f71057b8aff0b0778ef2ca934ea9d0f37daddade2d823a4"
+ "d8e362721082e279d003b575ee59fd050d105dfd71cd63154efe431a0"
+ "869178d9811f4f231dc5dcf3b0ec0f2b0f9896c32ec6c7ee7d60aa971"
+ "09e09224907328d4e6acd10117e45774406c4c947da8020649c3168f6"
+ "90e0bd6e91ac67074d1d436b58ae374523deaf6c93c1e6920db4a080b"
+ "744804bb073cecfe83fa9398cf150afa286dc7eb7949750cf5001ce10"
+ "4e9187f7e16859afa8fd0d775ae",
+ 16,
+ ),
),
y=int(
- '814824e435e1e6f38daa239aad6dad21033afce6a3ebd35c1359348a0f241'
- '8871968c2babfc2baf47742148828f8612183178f126504da73566b6bab33'
- 'ba1f124c15aa461555c2451d86c94ee21c3e3fc24c55527e01b1f03adcdd8'
- 'ec5cb08082803a7b6a829c3e99eeb332a2cf5c035b0ce0078d3d414d31fa4'
- '7e9726be2989b8d06da2e6cd363f5a7d1515e3f4925e0b32adeae3025cc5a'
- '996f6fd27494ea408763de48f3bb39f6a06514b019899b312ec570851637b'
- '8865cff3a52bf5d54ad5a19e6e400a2d33251055d0a440b50d53f4791391d'
- 'c754ad02b9eab74c46b4903f9d76f824339914db108057af7cde657d41766'
- 'a99991ac8787694f4185d6f91d7627048f827b405ec67bf2fe56141c4c581'
- 'd8c317333624e073e5879a82437cb0c7b435c0ce434e15965db1315d64895'
- '991e6bbe7dac040c42052408bbc53423fd31098248a58f8a67da3a39895cd'
- '0cc927515d044c1e3cb6a3259c3d0da354cce89ea3552c59609db10ee9899'
- '86527436af21d9485ddf25f90f7dff6d2bae', 16
- )
+ "814824e435e1e6f38daa239aad6dad21033afce6a3ebd35c1359348a0f241"
+ "8871968c2babfc2baf47742148828f8612183178f126504da73566b6bab33"
+ "ba1f124c15aa461555c2451d86c94ee21c3e3fc24c55527e01b1f03adcdd8"
+ "ec5cb08082803a7b6a829c3e99eeb332a2cf5c035b0ce0078d3d414d31fa4"
+ "7e9726be2989b8d06da2e6cd363f5a7d1515e3f4925e0b32adeae3025cc5a"
+ "996f6fd27494ea408763de48f3bb39f6a06514b019899b312ec570851637b"
+ "8865cff3a52bf5d54ad5a19e6e400a2d33251055d0a440b50d53f4791391d"
+ "c754ad02b9eab74c46b4903f9d76f824339914db108057af7cde657d41766"
+ "a99991ac8787694f4185d6f91d7627048f827b405ec67bf2fe56141c4c581"
+ "d8c317333624e073e5879a82437cb0c7b435c0ce434e15965db1315d64895"
+ "991e6bbe7dac040c42052408bbc53423fd31098248a58f8a67da3a39895cd"
+ "0cc927515d044c1e3cb6a3259c3d0da354cce89ea3552c59609db10ee9899"
+ "86527436af21d9485ddf25f90f7dff6d2bae",
+ 16,
+ ),
),
x=int(
- 'b2764c46113983777d3e7e97589f1303806d14ad9f2f1ef033097de954b17706',
- 16
- )
+ "b2764c46113983777d3e7e97589f1303806d14ad9f2f1ef033097de954b17706", 16
+ ),
)
diff --git a/tests/hazmat/primitives/fixtures_ec.py b/tests/hazmat/primitives/fixtures_ec.py
index 21c6903..d1d0a46 100644
--- a/tests/hazmat/primitives/fixtures_ec.py
+++ b/tests/hazmat/primitives/fixtures_ec.py
@@ -9,288 +9,272 @@
EC_KEY_SECT571R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '213997069697108634621868251335076179190383272087548888968788698953'
- '131928375431570122753130054966269038244076049869476736547896549201'
- '7388482714521707824160638375437887802901'
+ "213997069697108634621868251335076179190383272087548888968788698953"
+ "131928375431570122753130054966269038244076049869476736547896549201"
+ "7388482714521707824160638375437887802901"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT571R1(),
x=int(
- '42585672410900520895287019432267514156432686681290164230262278'
- '54789182447139054594501570747809649335533486119017169439209005'
- '883737780433424425566023654583165324498640038089'
+ "42585672410900520895287019432267514156432686681290164230262278"
+ "54789182447139054594501570747809649335533486119017169439209005"
+ "883737780433424425566023654583165324498640038089"
),
y=int(
- '13822523320209387572500458104799806851658024537477228250738334'
- '46977851514777531296572763848253279034733550774927720436494321'
- '97281333379623823457479233585424800362717541750'
- )
- )
+ "13822523320209387572500458104799806851658024537477228250738334"
+ "46977851514777531296572763848253279034733550774927720436494321"
+ "97281333379623823457479233585424800362717541750"
+ ),
+ ),
)
EC_KEY_SECT409R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '604993237916498765317587097853603474519114726157206838874832379003'
- '281871982139714656205843929472002062791572217653118715727'
+ "604993237916498765317587097853603474519114726157206838874832379003"
+ "281871982139714656205843929472002062791572217653118715727"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT409R1(),
x=int(
- '76237701339268928039087238870073679814646664010783544301589269'
- '2272579213400205907766385199643053767195204247826349822350081'
+ "76237701339268928039087238870073679814646664010783544301589269"
+ "2272579213400205907766385199643053767195204247826349822350081"
),
y=int(
- '10056668929618383045204866060110626563392345494925302478351744'
- '01475129090774493235522729123877384838835703483224447476728811'
- )
- )
+ "10056668929618383045204866060110626563392345494925302478351744"
+ "01475129090774493235522729123877384838835703483224447476728811"
+ ),
+ ),
)
EC_KEY_SECT283R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '589705077255658434962118789801402573495547207239917043241273753671'
- '0603230261342427657'
+ "589705077255658434962118789801402573495547207239917043241273753671"
+ "0603230261342427657"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT283R1(),
x=int(
- '10694213430317013187241490088760888472172922291550831393222973'
- '531614941756901942108493'
+ "10694213430317013187241490088760888472172922291550831393222973"
+ "531614941756901942108493"
),
y=int(
- '11461553100313943515373601367527399649593366728262918214942116'
- '4359557613202950705170'
- )
- )
+ "11461553100313943515373601367527399649593366728262918214942116"
+ "4359557613202950705170"
+ ),
+ ),
)
EC_KEY_SECT233R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '343470067105388144757135261232658742142830154753739648095101899829'
- '8288'
+ "343470067105388144757135261232658742142830154753739648095101899829"
+ "8288"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT233R1(),
x=int(
- '74494951569151557692195071465128140646140765188698294062550374'
- '71118267'
+ "74494951569151557692195071465128140646140765188698294062550374"
+ "71118267"
),
y=int(
- '48699150823022962508544923825876164485917001162461401797511748'
- '44872205'
- )
- )
+ "48699150823022962508544923825876164485917001162461401797511748"
+ "44872205"
+ ),
+ ),
)
EC_KEY_SECT163R2 = ec.EllipticCurvePrivateNumbers(
- private_value=int(
- '11788436193853888218177032687141056784083668635'
- ),
+ private_value=int("11788436193853888218177032687141056784083668635"),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT163R2(),
- x=int(
- '5247234453330640212490501030772203801908103222463'
- ),
- y=int(
- '3172513801099088785224248292142866317754124455206'
- )
- )
+ x=int("5247234453330640212490501030772203801908103222463"),
+ y=int("3172513801099088785224248292142866317754124455206"),
+ ),
)
EC_KEY_SECT571K1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '592811051234886966121888758661314648311634839499582476726008738218'
- '165015048237934517672316204181933804884636855291118594744334592153'
- '883208936227914544246799490897169723387'
+ "592811051234886966121888758661314648311634839499582476726008738218"
+ "165015048237934517672316204181933804884636855291118594744334592153"
+ "883208936227914544246799490897169723387"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT571K1(),
x=int(
- '81362471461936552203898455874182916939857774872643607884250052'
- '29301336524105230729653881789373412990921493551253481866317181'
- '50644729351721577822595637058949405764944491655'
+ "81362471461936552203898455874182916939857774872643607884250052"
+ "29301336524105230729653881789373412990921493551253481866317181"
+ "50644729351721577822595637058949405764944491655"
),
y=int(
- '14058041260812945396067821061063618047896814719828637241661260'
- '31235681542401975593036630733881695595289523801041910183736211'
- '587294494888450327374439795428519848065589000434'
- )
- )
+ "14058041260812945396067821061063618047896814719828637241661260"
+ "31235681542401975593036630733881695595289523801041910183736211"
+ "587294494888450327374439795428519848065589000434"
+ ),
+ ),
)
EC_KEY_SECT409K1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '110321743150399087059465162400463719641470113494908091197354523708'
- '934106732952992153105338671368548199643686444619485307877'
+ "110321743150399087059465162400463719641470113494908091197354523708"
+ "934106732952992153105338671368548199643686444619485307877"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT409K1(),
x=int(
- '62280214209410363493525178797944995742119600145953755916426161'
- '0790364158569265348038207313261547476506319796469776797725796'
+ "62280214209410363493525178797944995742119600145953755916426161"
+ "0790364158569265348038207313261547476506319796469776797725796"
),
y=int(
- '46653883749102474289095010108777579907422472804577185369332018'
- '7318642669590280811057512951467298158275464566214288556375885'
- )
- )
+ "46653883749102474289095010108777579907422472804577185369332018"
+ "7318642669590280811057512951467298158275464566214288556375885"
+ ),
+ ),
)
EC_KEY_SECT283K1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '182508394415444014156574733141549331538128234395356466108310015130'
- '3868915489347291850'
+ "182508394415444014156574733141549331538128234395356466108310015130"
+ "3868915489347291850"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT283K1(),
x=int(
- '31141647206111886426350703123670451554123180910379592764773885'
- '2959123367428352287032'
+ "31141647206111886426350703123670451554123180910379592764773885"
+ "2959123367428352287032"
),
y=int(
- '71787460144483665964585187837283963089964760704065205376175384'
- '58957627834444017112582'
- )
- )
+ "71787460144483665964585187837283963089964760704065205376175384"
+ "58957627834444017112582"
+ ),
+ ),
)
EC_KEY_SECT233K1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '172670089647474613734091436081960550801254775902629891892394471086'
- '2070'
+ "172670089647474613734091436081960550801254775902629891892394471086"
+ "2070"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT233K1(),
x=int(
- '55693911474339510991521579392202889561373678973929426354737048'
- '68129172'
+ "55693911474339510991521579392202889561373678973929426354737048"
+ "68129172"
),
y=int(
- '11025856248546376145959939911850923631416718241836051344384802'
- '737277815'
- )
- )
+ "11025856248546376145959939911850923631416718241836051344384802"
+ "737277815"
+ ),
+ ),
)
EC_KEY_SECT163K1 = ec.EllipticCurvePrivateNumbers(
- private_value=int(
- '3699303791425402204035307605170569820290317991287'
- ),
+ private_value=int("3699303791425402204035307605170569820290317991287"),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECT163K1(),
- x=int(
- '4479755902310063321544063130576409926980094120721'
- ),
- y=int(
- '3051218481937171839039826690648109285113977745779'
- )
- )
+ x=int("4479755902310063321544063130576409926980094120721"),
+ y=int("3051218481937171839039826690648109285113977745779"),
+ ),
)
EC_KEY_SECP521R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '662751235215460886290293902658128847495347691199214706697089140769'
- '672273950767961331442265530524063943548846724348048614239791498442'
- '5997823106818915698960565'
+ "662751235215460886290293902658128847495347691199214706697089140769"
+ "672273950767961331442265530524063943548846724348048614239791498442"
+ "5997823106818915698960565"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECP521R1(),
x=int(
- '12944742826257420846659527752683763193401384271391513286022917'
- '29910013082920512632908350502247952686156279140016049549948975'
- '670668730618745449113644014505462'
+ "12944742826257420846659527752683763193401384271391513286022917"
+ "29910013082920512632908350502247952686156279140016049549948975"
+ "670668730618745449113644014505462"
),
y=int(
- '10784108810271976186737587749436295782985563640368689081052886'
- '16296815984553198866894145509329328086635278430266482551941240'
- '591605833440825557820439734509311'
- )
- )
+ "10784108810271976186737587749436295782985563640368689081052886"
+ "16296815984553198866894145509329328086635278430266482551941240"
+ "591605833440825557820439734509311"
+ ),
+ ),
)
EC_KEY_SECP384R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '280814107134858470598753916394807521398239633534281633982576099083'
- '35787109896602102090002196616273211495718603965098'
+ "280814107134858470598753916394807521398239633534281633982576099083"
+ "35787109896602102090002196616273211495718603965098"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECP384R1(),
x=int(
- '10036914308591746758780165503819213553101287571902957054148542'
- '504671046744460374996612408381962208627004841444205030'
+ "10036914308591746758780165503819213553101287571902957054148542"
+ "504671046744460374996612408381962208627004841444205030"
),
y=int(
- '17337335659928075994560513699823544906448896792102247714689323'
- '575406618073069185107088229463828921069465902299522926'
- )
- )
+ "17337335659928075994560513699823544906448896792102247714689323"
+ "575406618073069185107088229463828921069465902299522926"
+ ),
+ ),
)
EC_KEY_SECP256R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '271032978511595617649844168316234344656921218699414461240502635010'
- '25776962849'
+ "271032978511595617649844168316234344656921218699414461240502635010"
+ "25776962849"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECP256R1(),
x=int(
- '49325986169170464532722748935508337546545346352733747948730305'
- '442770101441241'
+ "49325986169170464532722748935508337546545346352733747948730305"
+ "442770101441241"
),
y=int(
- '51709162888529903487188595007092772817469799707382623884187518'
- '455962250433661'
- )
- )
+ "51709162888529903487188595007092772817469799707382623884187518"
+ "455962250433661"
+ ),
+ ),
)
EC_KEY_SECP256K1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '683341569008473593765879222774207677458810362976327530563215318048'
- '64380736732'
+ "683341569008473593765879222774207677458810362976327530563215318048"
+ "64380736732"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECP256K1(),
x=int(
- '59251322975795306609293064274738085741081547489119277536110995'
- '120127593127884'
+ "59251322975795306609293064274738085741081547489119277536110995"
+ "120127593127884"
),
y=int(
- '10334192001480392039227801832201340147605940717841294644187071'
- '8261641142297801'
- )
- )
+ "10334192001480392039227801832201340147605940717841294644187071"
+ "8261641142297801"
+ ),
+ ),
)
EC_KEY_SECP224R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '234854340492774342642505519082413233282383066880756900834047566251'
- '50'
+ "234854340492774342642505519082413233282383066880756900834047566251"
+ "50"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECP224R1(),
x=int(
- '51165676638271204691095081341581621487998422645261573824239666'
- '1214'
+ "51165676638271204691095081341581621487998422645261573824239666"
+ "1214"
),
y=int(
- '14936601450555711309158397172719963843891926209168533453717969'
- '1265'
- )
- )
+ "14936601450555711309158397172719963843891926209168533453717969"
+ "1265"
+ ),
+ ),
)
EC_KEY_SECP192R1 = ec.EllipticCurvePrivateNumbers(
private_value=int(
- '4534766128536179420071447168915990251715442361606049349869'
+ "4534766128536179420071447168915990251715442361606049349869"
),
public_numbers=ec.EllipticCurvePublicNumbers(
curve=ec.SECP192R1(),
- x=int(
- '5415069751170397888083674339683360671310515485781457536999'
- ),
- y=int(
- '18671605334415960797751252911958331304288357195986572776'
- )
- )
+ x=int("5415069751170397888083674339683360671310515485781457536999"),
+ y=int("18671605334415960797751252911958331304288357195986572776"),
+ ),
)
diff --git a/tests/hazmat/primitives/fixtures_rsa.py b/tests/hazmat/primitives/fixtures_rsa.py
index a531783..2c06272 100644
--- a/tests/hazmat/primitives/fixtures_rsa.py
+++ b/tests/hazmat/primitives/fixtures_rsa.py
@@ -5,7 +5,8 @@
from __future__ import absolute_import, division, print_function
from cryptography.hazmat.primitives.asymmetric.rsa import (
- RSAPrivateNumbers, RSAPublicNumbers
+ RSAPrivateNumbers,
+ RSAPublicNumbers,
)
@@ -18,7 +19,8 @@
),
d=int(
"272869352cacf9c866c4e107acc95d4c608ca91460a93d28588d51cfccc07f449"
- "18bbe7660f9f16adc2b4ed36ca310ef3d63b79bd447456e3505736a45a6ed21", 16
+ "18bbe7660f9f16adc2b4ed36ca310ef3d63b79bd447456e3505736a45a6ed21",
+ 16,
),
dmp1=int(
"addff2ec7564c6b64bc670d250b6f24b0b8db6b2810099813b7e7658cecf5c39", 16
@@ -34,178 +36,239 @@
n=int(
"ae5411f963c50e3267fafcf76381c8b1e5f7b741fdb2a544bcf48bd607b10c991"
"90caeb8011dc22cf83d921da55ec32bd05cac3ee02ca5e1dbef93952850b525",
- 16
+ 16,
),
- )
+ ),
)
RSA_KEY_512_ALT = RSAPrivateNumbers(
p=int(
- "febe19c29a0b50fefa4f7b1832f84df1caf9be8242da25c9d689e18226e67ce5",
- 16),
+ "febe19c29a0b50fefa4f7b1832f84df1caf9be8242da25c9d689e18226e67ce5", 16
+ ),
q=int(
- "eb616c639dd999feda26517e1c77b6878f363fe828c4e6670ec1787f28b1e731",
- 16),
+ "eb616c639dd999feda26517e1c77b6878f363fe828c4e6670ec1787f28b1e731", 16
+ ),
d=int(
"80edecfde704a806445a4cc782b85d3f36f17558f385654ea767f006470fdfcbda5e2"
- "206839289d3f419b4e4fb8e1acee1b4fb9c591f69b64ec83937f5829241", 16),
+ "206839289d3f419b4e4fb8e1acee1b4fb9c591f69b64ec83937f5829241",
+ 16,
+ ),
dmp1=int(
- "7f4fa06e2a3077a54691cc5216bf13ad40a4b9fa3dd0ea4bca259487484baea5",
- 16),
+ "7f4fa06e2a3077a54691cc5216bf13ad40a4b9fa3dd0ea4bca259487484baea5", 16
+ ),
dmq1=int(
- "35eaa70d5a8711c352ed1c15ab27b0e3f46614d575214535ae279b166597fac1",
- 16),
+ "35eaa70d5a8711c352ed1c15ab27b0e3f46614d575214535ae279b166597fac1", 16
+ ),
iqmp=int(
- "cc1f272de6846851ec80cb89a02dbac78f44b47bc08f53b67b4651a3acde8b19",
- 16),
+ "cc1f272de6846851ec80cb89a02dbac78f44b47bc08f53b67b4651a3acde8b19", 16
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
"ea397388b999ef0f7e7416fa000367efd9a0ba0deddd3f8160d1c36d62267f210"
"fbd9c97abeb6654450ff03e7601b8caa6c6f4cba18f0b52c179d17e8f258ad5",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_522 = RSAPrivateNumbers(
p=int(
"1a8aab9a069f92b52fdf05824f2846223dc27adfc806716a247a77d4c36885e4bf",
- 16),
+ 16,
+ ),
q=int(
"19e8d620d177ec54cdb733bb1915e72ef644b1202b889ceb524613efa49c07eb4f",
- 16),
+ 16,
+ ),
d=int(
"10b8a7c0a92c1ae2d678097d69db3bfa966b541fb857468291d48d1b52397ea2bac0d"
- "4370c159015c7219e3806a01bbafaffdd46f86e3da1e2d1fe80a0369ccd745", 16),
+ "4370c159015c7219e3806a01bbafaffdd46f86e3da1e2d1fe80a0369ccd745",
+ 16,
+ ),
dmp1=int(
- "3eb6277f66e6e2dcf89f1b8529431f730839dbd9a3e49555159bc8470eee886e5",
- 16),
+ "3eb6277f66e6e2dcf89f1b8529431f730839dbd9a3e49555159bc8470eee886e5", 16
+ ),
dmq1=int(
"184b4d74aa54c361e51eb23fee4eae5e4786b37b11b6e0447af9c0b9c4e4953c5b",
- 16),
+ 16,
+ ),
iqmp=int(
- "f80e9ab4fa7b35d0d232ef51c4736d1f2dcf2c7b1dd8716211b1bf1337e74f8ae",
- 16),
+ "f80e9ab4fa7b35d0d232ef51c4736d1f2dcf2c7b1dd8716211b1bf1337e74f8ae", 16
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
"2afaea0e0bb6fca037da7d190b5270a6c665bc18e7a456f7e69beaac4433db748"
"ba99acdd14697e453bca596eb35b47f2d48f1f85ef08ce5109dad557a9cf85ebf"
- "1", 16),
+ "1",
+ 16,
+ ),
),
)
RSA_KEY_599 = RSAPrivateNumbers(
p=int(
"cf95d20be0c7af69f4b3d909f65d858c26d1a7ef34da8e3977f4fa230580e58814b54"
- "24be99", 16),
+ "24be99",
+ 16,
+ ),
q=int(
"6052be4b28debd4265fe12ace5aa4a0c4eb8d63ff8853c66824b35622161eb48a3bc8"
- "c3ada5", 16),
+ "c3ada5",
+ 16,
+ ),
d=int(
"69d9adc465e61585d3142d7cc8dd30605e8d1cbbf31009bc2cd5538dc40528d5d68ee"
"fe6a42d23674b6ec76e192351bf368c8968f0392110bf1c2825dbcff071270b80adcc"
- "fa1d19d00a1", 16),
+ "fa1d19d00a1",
+ 16,
+ ),
dmp1=int(
"a86d10edde456687fba968b1f298d2e07226adb1221b2a466a93f3d83280f0bb46c20"
- "2b6811", 16),
+ "2b6811",
+ 16,
+ ),
dmq1=int(
"40d570e08611e6b1da94b95d46f8e7fe80be48f7a5ff8838375b08039514a399b11c2"
- "80735", 16),
+ "80735",
+ 16,
+ ),
iqmp=int(
"cd051cb0ea68b88765c041262ace2ec4db11dab14afd192742e34d5da3328637fabdf"
- "bae26e", 16),
+ "bae26e",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
"4e1b470fe00642426f3808e74c959632dd67855a4c503c5b7876ccf4dc7f6a1a4"
"9107b90d26daf0a7879a6858218345fbc6e59f01cd095ca5647c27c25265e6c47"
- "4fea89537191c7073d9d", 16),
- )
+ "4fea89537191c7073d9d",
+ 16,
+ ),
+ ),
)
RSA_KEY_745 = RSAPrivateNumbers(
p=int(
"1c5a0cfe9a86debd19eca33ba961f15bc598aa7983a545ce775b933afc89eb51bcf90"
- "836257fdd060d4b383240241d", 16
+ "836257fdd060d4b383240241d",
+ 16,
),
q=int(
"fb2634f657f82ee6b70553382c4e2ed26b947c97ce2f0016f1b282cf2998184ad0527"
- "a9eead826dd95fe06b57a025", 16
+ "a9eead826dd95fe06b57a025",
+ 16,
),
d=int(
"402f30f976bc07d15ff0779abff127b20a8b6b1d0024cc2ad8b6762d38f174f81e792"
"3b49d80bdbdd80d9675cbc7b2793ec199a0430eb5c84604dacfdb29259ae6a1a44676"
- "22f0b23d4cb0f5cb1db4b8173c8d9d3e57a74dbd200d2141", 16),
+ "22f0b23d4cb0f5cb1db4b8173c8d9d3e57a74dbd200d2141",
+ 16,
+ ),
dmp1=int(
"e5e95b7751a6649f199be21bef7a51c9e49821d945b6fc5f538b4a670d8762c375b00"
- "8e70f31d52b3ea2bd14c3101", 16),
+ "8e70f31d52b3ea2bd14c3101",
+ 16,
+ ),
dmq1=int(
"12b85d5843645f72990fcf8d2f58408b34b3a3b9d9078dd527fceb5d2fb7839008092"
- "dd4aca2a1fb00542801dcef5", 16),
+ "dd4aca2a1fb00542801dcef5",
+ 16,
+ ),
iqmp=int(
"5672740d947f621fc7969e3a44ec26736f3f819863d330e63e9409e139d20753551ac"
- "c16544dd2bdadb9dee917440", 16),
+ "c16544dd2bdadb9dee917440",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
"1bd085f92237774d34013b477ceebbb2f2feca71118db9b7429341477947e7b1d"
"04e8c43ede3c52bb25781af58d4ff81289f301eac62dc3bcd7dafd7a4d5304e9f"
- "308e766952fbf2b62373e66611fa53189987dbef9f7243dcbbeb25831", 16),
- )
+ "308e766952fbf2b62373e66611fa53189987dbef9f7243dcbbeb25831",
+ 16,
+ ),
+ ),
)
RSA_KEY_768 = RSAPrivateNumbers(
p=int(
"f80c0061b607f93206b68e208906498d68c6e396faf457150cf975c8f849848465869"
- "7ecd402313397088044c4c2071b", 16),
+ "7ecd402313397088044c4c2071b",
+ 16,
+ ),
q=int(
"e5b5dbecc93c6d306fc14e6aa9737f9be2728bc1a326a8713d2849b34c1cb54c63468"
- "3a68abb1d345dbf15a3c492cf55", 16),
+ "3a68abb1d345dbf15a3c492cf55",
+ 16,
+ ),
d=int(
"d44601442255ffa331212c60385b5e898555c75c0272632ff42d57c4b16ca97dbca9f"
"d6d99cd2c9fd298df155ed5141b4be06c651934076133331d4564d73faed7ce98e283"
- "2f7ce3949bc183be7e7ca34f6dd04a9098b6c73649394b0a76c541", 16),
+ "2f7ce3949bc183be7e7ca34f6dd04a9098b6c73649394b0a76c541",
+ 16,
+ ),
dmp1=int(
"a5763406fa0b65929661ce7b2b8c73220e43a5ebbfe99ff15ddf464fd238105ad4f2a"
- "c83818518d70627d8908703bb03", 16),
+ "c83818518d70627d8908703bb03",
+ 16,
+ ),
dmq1=int(
"cb467a9ef899a39a685aecd4d0ad27b0bfdc53b68075363c373d8eb2bed8eccaf3533"
- "42f4db735a9e087b7539c21ba9d", 16),
+ "42f4db735a9e087b7539c21ba9d",
+ 16,
+ ),
iqmp=int(
"5fe86bd3aee0c4d09ef11e0530a78a4534c9b833422813b5c934a450c8e564d8097a0"
- "6fd74f1ebe2d5573782093f587a", 16),
+ "6fd74f1ebe2d5573782093f587a",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
"de92f1eb5f4abf426b6cac9dd1e9bf57132a4988b4ed3f8aecc15e251028bd6df"
"46eb97c711624af7db15e6430894d1b640c13929329241ee094f5a4fe1a20bc9b"
"75232320a72bc567207ec54d6b48dccb19737cf63acc1021abb337f19130f7",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1024 = RSAPrivateNumbers(
p=int(
"ea4d9d9a1a068be44b9a5f8f6de0512b2c5ba1fb804a4655babba688e6e890b347c1a"
- "7426685a929337f513ae4256f0b7e5022d642237f960c5b24b96bee8e51", 16),
+ "7426685a929337f513ae4256f0b7e5022d642237f960c5b24b96bee8e51",
+ 16,
+ ),
q=int(
"cffb33e400d6f08b410d69deb18a85cf0ed88fcca9f32d6f2f66c62143d49aff92c11"
- "4de937d4f1f62d4635ee89af99ce86d38a2b05310f3857c7b5d586ac8f9", 16),
+ "4de937d4f1f62d4635ee89af99ce86d38a2b05310f3857c7b5d586ac8f9",
+ 16,
+ ),
d=int(
"3d12d46d04ce942fb99be7bf30587b8cd3e21d75a2720e7bda1b867f1d418d91d8b9f"
"e1c00181fdde94f2faf33b4e6f800a1b3ae3b972ccb6d5079dcb6c794070ac8306d59"
"c00b58b7a9a81122a6b055832de7c72334a07494d8e7c9fbeed2cc37e011d9e6bfc6e"
- "9bcddbef7f0f5771d9cf82cd4b268c97ec684575c24b6c881", 16),
+ "9bcddbef7f0f5771d9cf82cd4b268c97ec684575c24b6c881",
+ 16,
+ ),
dmp1=int(
"470f2b11257b7ec9ca34136f487f939e6861920ad8a9ae132a02e74af5dceaa5b4c98"
- "2949ccb44b67e2bcad2f58674db237fe250e0d62b47b28fa1dfaa603b41", 16),
+ "2949ccb44b67e2bcad2f58674db237fe250e0d62b47b28fa1dfaa603b41",
+ 16,
+ ),
dmq1=int(
"c616e8317d6b3ae8272973709b80e8397256697ff14ea03389de454f619f99915a617"
- "45319fefbe154ec1d49441a772c2f63f7d15c478199afc60469bfd0d561", 16),
+ "45319fefbe154ec1d49441a772c2f63f7d15c478199afc60469bfd0d561",
+ 16,
+ ),
iqmp=int(
"d15e7c9ad357dfcd5dbdc8427680daf1006761bcfba93a7f86589ad88832a8d564b1c"
- "d4291a658c96fbaea7ca588795820902d85caebd49c2d731e3fe0243130", 16),
+ "d4291a658c96fbaea7ca588795820902d85caebd49c2d731e3fe0243130",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -213,31 +276,44 @@
"ede07be3bed0e355d48e0dfab1e4fb5187adf42d7d3fb0401c082acb8481bf17f"
"0e871f8877be04c3a1197d40aa260e2e0c48ed3fd2b93dc3fc0867591f67f3cd6"
"0a77adee1d68a8c3730a5702485f6ac9ede7f0fd2918e037ee4cc1fc1b4c9",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1025 = RSAPrivateNumbers(
p=int(
"18e9bfb7071725da04d31c103fa3563648c69def43a204989214eb57b0c8b299f9ef3"
- "5dda79a62d8d67fd2a9b69fbd8d0490aa2edc1e111a2b8eb7c737bb691a5", 16),
+ "5dda79a62d8d67fd2a9b69fbd8d0490aa2edc1e111a2b8eb7c737bb691a5",
+ 16,
+ ),
q=int(
"d8eccaeeb95815f3079d13685f3f72ca2bf2550b349518049421375df88ca9bbb4ba8"
- "cb0e3502203c9eeae174112509153445d251313e4711a102818c66fcbb7", 16),
+ "cb0e3502203c9eeae174112509153445d251313e4711a102818c66fcbb7",
+ 16,
+ ),
d=int(
"fe9ac54910b8b1bc948a03511c54cab206a1d36d50d591124109a48abb7480977ccb0"
"47b4d4f1ce7b0805df2d4fa3fe425f49b78535a11f4b87a4eba0638b3340c23d4e6b2"
"1ecebe9d5364ea6ead2d47b27836019e6ecb407000a50dc95a8614c9d0031a6e3a524"
- "d2345cfb76e15c1f69d5ba35bdfb6ec63bcb115a757ef79d9", 16),
+ "d2345cfb76e15c1f69d5ba35bdfb6ec63bcb115a757ef79d9",
+ 16,
+ ),
dmp1=int(
"18537e81006a68ea76d590cc88e73bd26bc38d09c977959748e5265c0ce21c0b5fd26"
- "53d975f97ef759b809f791487a8fff1264bf561627fb4527a3f0bbb72c85", 16),
+ "53d975f97ef759b809f791487a8fff1264bf561627fb4527a3f0bbb72c85",
+ 16,
+ ),
dmq1=int(
"c807eac5a1f1e1239f04b04dd16eff9a00565127a91046fa89e1eb5d6301cace85447"
- "4d1f47b0332bd35b4214b66e9166953241538f761f30d969272ee214f17", 16),
+ "4d1f47b0332bd35b4214b66e9166953241538f761f30d969272ee214f17",
+ 16,
+ ),
iqmp=int(
"133aa74dd41fe70fa244f07d0c4091a22f8c8f0134fe6aea9ec8b55383b758fefe358"
- "2beec36eca91715eee7d21931f24fa9e97e8e3a50f9cd0f731574a5eafcc", 16),
+ "2beec36eca91715eee7d21931f24fa9e97e8e3a50f9cd0f731574a5eafcc",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -245,31 +321,44 @@
"bf276fe3523f38f5ddaf3ea9aa88486a9d8760ff732489075862bee0e599de5c5"
"f509b4519f4f446521bad15cd279a498fe1e89107ce0d237e3103d7c5eb801666"
"42e2924b152aebff97b71fdd2d68ebb45034cc784e2e822ff6d1edf98af3f3",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1026 = RSAPrivateNumbers(
p=int(
"1fcbfb8719c5bdb5fe3eb0937c76bb096e750b9442dfe31d6a877a13aed2a6a4e9f79"
- "40f815f1c307dd6bc2b4b207bb6fe5be3a15bd2875a957492ce197cdedb1", 16),
+ "40f815f1c307dd6bc2b4b207bb6fe5be3a15bd2875a957492ce197cdedb1",
+ 16,
+ ),
q=int(
"1f704a0f6b8966dd52582fdc08227dd3dbaeaa781918b41144b692711091b4ca4eb62"
- "985c3513853828ce8739001dfba9a9a7f1a23cbcaf74280be925e2e7b50d", 16),
+ "985c3513853828ce8739001dfba9a9a7f1a23cbcaf74280be925e2e7b50d",
+ 16,
+ ),
d=int(
"c67975e35a1d0d0b3ebfca736262cf91990cb31cf4ac473c0c816f3bc2720bcba2475"
"e8d0de8535d257816c0fc53afc1b597eada8b229069d6ef2792fc23f59ffb4dc6c3d9"
"0a3c462082025a4cba7561296dd3d8870c4440d779406f00879afe2c681e7f5ee055e"
- "ff829e6e55883ec20830c72300762e6e3a333d94b4dbe4501", 16),
+ "ff829e6e55883ec20830c72300762e6e3a333d94b4dbe4501",
+ 16,
+ ),
dmp1=int(
"314730ca7066c55d086a9fbdf3670ef7cef816b9efea8b514b882ae9d647217cf41d7"
- "e9989269dc9893d02e315cb81f058c49043c2cac47adea58bdf5e20e841", 16),
+ "e9989269dc9893d02e315cb81f058c49043c2cac47adea58bdf5e20e841",
+ 16,
+ ),
dmq1=int(
"1da28a9d687ff7cfeebc2439240de7505a8796376968c8ec723a2b669af8ce53d9c88"
- "af18540bd78b2da429014923fa435f22697ac60812d7ca9c17a557f394cd", 16),
+ "af18540bd78b2da429014923fa435f22697ac60812d7ca9c17a557f394cd",
+ 16,
+ ),
iqmp=int(
"727947b57b8a36acd85180522f1b381bce5fdbd962743b3b14af98a36771a80f58ddd"
- "62675d72a5935190da9ddc6fd6d6d5e9e9f805a2e92ab8d56b820493cdf", 16),
+ "62675d72a5935190da9ddc6fd6d6d5e9e9f805a2e92ab8d56b820493cdf",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -277,31 +366,44 @@
"9cfae6ab0446da18e26f33e1d753bc1cc03585c100cf0ab5ef056695706fc8b0c"
"9c710cd73fe6e5beda70f515a96fabd3cc5ac49efcb2594b220ff3b603fcd927f"
"6a0838ef04bf52f3ed9eab801f09e5aed1613ddeb946ed0fbb02060b3a36fd",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1027 = RSAPrivateNumbers(
p=int(
"30135e54cfb072c3d3eaf2000f3ed92ceafc85efc867b9d4bf5612f2978c432040093"
- "4829f741c0f002b54af2a4433ff872b6321ef00ff1e72cba4e0ced937c7d", 16),
+ "4829f741c0f002b54af2a4433ff872b6321ef00ff1e72cba4e0ced937c7d",
+ 16,
+ ),
q=int(
"1d01a8aead6f86b78c875f18edd74214e06535d65da054aeb8e1851d6f3319b4fb6d8"
- "6b01e07d19f8261a1ded7dc08116345509ab9790e3f13e65c037e5bb7e27", 16),
+ "6b01e07d19f8261a1ded7dc08116345509ab9790e3f13e65c037e5bb7e27",
+ 16,
+ ),
d=int(
"21cf4477df79561c7818731da9b9c88cd793f1b4b8e175bd0bfb9c0941a4dc648ecf1"
"6d96b35166c9ea116f4c2eb33ce1c231e641a37c25e54c17027bdec08ddafcb83642e"
"795a0dd133155ccc5eed03b6e745930d9ac7cfe91f9045149f33295af03a2198c660f"
- "08d8150d13ce0e2eb02f21ac75d63b55822f77bd5be8d07619", 16),
+ "08d8150d13ce0e2eb02f21ac75d63b55822f77bd5be8d07619",
+ 16,
+ ),
dmp1=int(
"173fb695931e845179511c18b546b265cb79b517c135902377281bdf9f34205e1f399"
- "4603ad63e9f6e7885ea73a929f03fa0d6bed943051ce76cddde2d89d434d", 16),
+ "4603ad63e9f6e7885ea73a929f03fa0d6bed943051ce76cddde2d89d434d",
+ 16,
+ ),
dmq1=int(
"10956b387b2621327da0c3c8ffea2af8be967ee25163222746c28115a406e632a7f12"
- "5a9397224f1fa5c116cd3a313e5c508d31db2deb83b6e082d213e33f7fcf", 16),
+ "5a9397224f1fa5c116cd3a313e5c508d31db2deb83b6e082d213e33f7fcf",
+ 16,
+ ),
iqmp=int(
"234f833949f2c0d797bc6a0e906331e17394fa8fbc8449395766d3a8d222cf6167c48"
- "8e7fe1fe9721d3e3b699a595c8e6f063d92bd840dbc84d763b2b37002109", 16),
+ "8e7fe1fe9721d3e3b699a595c8e6f063d92bd840dbc84d763b2b37002109",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -309,31 +411,44 @@
"0a5ae9f579ef1fd7e42937f921eb3123c4a045cc47a2159fbbf904783e654954c"
"42294c30a95c15db7c7b91f136244e548f62474b137087346c5522e54f226f49d"
"6c93bc58cb39972e41bde452bb3ae9d60eb93e5e1ce91d222138d9890c7d0b",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1028 = RSAPrivateNumbers(
p=int(
"359d17378fae8e9160097daee78a206bd52efe1b757c12a6da8026cc4fc4bb2620f12"
- "b8254f4db6aed8228be8ee3e5a27ec7d31048602f01edb00befd209e8c75", 16),
+ "b8254f4db6aed8228be8ee3e5a27ec7d31048602f01edb00befd209e8c75",
+ 16,
+ ),
q=int(
"33a2e70b93d397c46e63b273dcd3dcfa64291342a6ce896e1ec8f1c0edc44106550f3"
- "c06e7d3ca6ea29eccf3f6ab5ac6235c265313d6ea8e8767e6a343f616581", 16),
+ "c06e7d3ca6ea29eccf3f6ab5ac6235c265313d6ea8e8767e6a343f616581",
+ 16,
+ ),
d=int(
"880640088d331aa5c0f4cf2887809a420a2bc086e671e6ffe4e47a8c80792c038a314"
"9a8e45ef9a72816ab45b36e3af6800351067a6b2751843d4232413146bb575491463a"
"8addd06ce3d1bcf7028ec6c5d938c545a20f0a40214b5c574ca7e840062b2b5f8ed49"
- "4b144bb2113677c4b10519177fee1d4f5fb8a1c159b0b47c01", 16),
+ "4b144bb2113677c4b10519177fee1d4f5fb8a1c159b0b47c01",
+ 16,
+ ),
dmp1=int(
"75f8c52dad2c1cea26b8bba63236ee4059489e3d2db766136098bcc6b67fde8f77cd3"
- "640035107bfb1ffc6480983cfb84fe0c3be008424ebc968a7db7e01f005", 16),
+ "640035107bfb1ffc6480983cfb84fe0c3be008424ebc968a7db7e01f005",
+ 16,
+ ),
dmq1=int(
"3893c59469e4ede5cd0e6ff9837ca023ba9b46ff40c60ccf1bec10f7d38db5b1ba817"
- "6c41a3f750ec4203b711455aca06d1e0adffc5cffa42bb92c7cb77a6c01", 16),
+ "6c41a3f750ec4203b711455aca06d1e0adffc5cffa42bb92c7cb77a6c01",
+ 16,
+ ),
iqmp=int(
"ad32aafae3c962ac25459856dc8ef1f733c3df697eced29773677f435d186cf759d1a"
- "5563dd421ec47b4d7e7f12f29647c615166d9c43fc49001b29089344f65", 16),
+ "5563dd421ec47b4d7e7f12f29647c615166d9c43fc49001b29089344f65",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -341,31 +456,44 @@
"e3510c68073954d3ba4deb38643e7a820a4cf06e75f7f82eca545d412bd637819"
"45c28d406e95a6cced5ae924a8bfa4f3def3e0250d91246c269ec40c89c93a85a"
"cd3770ba4d2e774732f43abe94394de43fb57f93ca25f7a59d75d400a3eff5",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1029 = RSAPrivateNumbers(
p=int(
"66f33e513c0b6b6adbf041d037d9b1f0ebf8de52812a3ac397a963d3f71ba64b3ad04"
- "e4d4b5e377e6fa22febcac292c907dc8dcfe64c807fd9a7e3a698850d983", 16),
+ "e4d4b5e377e6fa22febcac292c907dc8dcfe64c807fd9a7e3a698850d983",
+ 16,
+ ),
q=int(
"3b47a89a19022461dcc2d3c05b501ee76955e8ce3cf821beb4afa85a21a26fd7203db"
- "deb8941f1c60ada39fd6799f6c07eb8554113f1020460ec40e93cd5f6b21", 16),
+ "deb8941f1c60ada39fd6799f6c07eb8554113f1020460ec40e93cd5f6b21",
+ 16,
+ ),
d=int(
"280c42af8b1c719821f2f6e2bf5f3dd53c81b1f3e1e7cc4fce6e2f830132da0665bde"
"bc1e307106b112b52ad5754867dddd028116cf4471bc14a58696b99524b1ad8f05b31"
"cf47256e54ab4399b6a073b2c0452441438dfddf47f3334c13c5ec86ece4d33409056"
- "139328fafa992fb5f5156f25f9b21d3e1c37f156d963d97e41", 16),
+ "139328fafa992fb5f5156f25f9b21d3e1c37f156d963d97e41",
+ 16,
+ ),
dmp1=int(
"198c7402a4ec10944c50ab8488d7b5991c767e75eb2817bd427dff10335ae141fa2e8"
- "7c016dc22d975cac229b9ffdf7d943ddfd3a04b8bf82e83c3b32c5698b11", 16),
+ "7c016dc22d975cac229b9ffdf7d943ddfd3a04b8bf82e83c3b32c5698b11",
+ 16,
+ ),
dmq1=int(
"15fd30c7687b68ef7c2a30cdeb913ec56c4757c218cf9a04d995470797ee5f3a17558"
- "fbb6d00af245d2631d893b382da48a72bc8a613024289895952ab245b0c1", 16),
+ "fbb6d00af245d2631d893b382da48a72bc8a613024289895952ab245b0c1",
+ 16,
+ ),
iqmp=int(
"4f8fde17e84557a3f4e242d889e898545ab55a1a8e075c9bb0220173ccffe84659abe"
- "a235104f82e32750309389d4a52af57dbb6e48d831917b6efeb190176570", 16),
+ "a235104f82e32750309389d4a52af57dbb6e48d831917b6efeb190176570",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -373,31 +501,44 @@
"99a9f74981c3eeaaf947d5c2d64a1a80f5c5108a49a715c3f7be95a016b8d3300"
"965ead4a4df76e642d761526803e9434d4ec61b10cb50526d4dcaef02593085de"
"d8c331c1b27b200a45628403065efcb2c0a0ca1f75d648d40a007fbfbf2cae3",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1030 = RSAPrivateNumbers(
p=int(
"6f4ac8a8172ef1154cf7f80b5e91de723c35a4c512860bfdbafcc3b994a2384bf7796"
- "3a2dd0480c7e04d5d418629651a0de8979add6f47b23da14c27a682b69c9", 16),
+ "3a2dd0480c7e04d5d418629651a0de8979add6f47b23da14c27a682b69c9",
+ 16,
+ ),
q=int(
"65a9f83e07dea5b633e036a9dccfb32c46bf53c81040a19c574c3680838fc6d28bde9"
- "55c0ff18b30481d4ab52a9f5e9f835459b1348bbb563ad90b15a682fadb3", 16),
+ "55c0ff18b30481d4ab52a9f5e9f835459b1348bbb563ad90b15a682fadb3",
+ 16,
+ ),
d=int(
"290db707b3e1a96445ae8ea93af55a9f211a54ebe52995c2eb28085d1e3f09c986e73"
"a00010c8e4785786eaaa5c85b98444bd93b585d0c24363ccc22c482e150a3fd900176"
"86968e4fa20423ae72823b0049defceccb39bb34aa4ef64e6b14463b76d6a871c859e"
- "37285455b94b8e1527d1525b1682ac6f7c8fd79d576c55318c1", 16),
+ "37285455b94b8e1527d1525b1682ac6f7c8fd79d576c55318c1",
+ 16,
+ ),
dmp1=int(
"23f7fa84010225dea98297032dac5d45745a2e07976605681acfe87e0920a8ab3caf5"
- "9d9602f3d63dc0584f75161fd8fff20c626c21c5e02a85282276a74628a9", 16),
+ "9d9602f3d63dc0584f75161fd8fff20c626c21c5e02a85282276a74628a9",
+ 16,
+ ),
dmq1=int(
"18ebb657765464a8aa44bf019a882b72a2110a77934c54915f70e6375088b10331982"
- "962bce1c7edd8ef9d3d95aa2566d2a99da6ebab890b95375919408d00f33", 16),
+ "962bce1c7edd8ef9d3d95aa2566d2a99da6ebab890b95375919408d00f33",
+ 16,
+ ),
iqmp=int(
"3d59d208743c74054151002d77dcdfc55af3d41357e89af88d7eef2767be54c290255"
- "9258d85cf2a1083c035a33e65a1ca46dc8b706847c1c6434cef7b71a9dae", 16),
+ "9258d85cf2a1083c035a33e65a1ca46dc8b706847c1c6434cef7b71a9dae",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -405,31 +546,44 @@
"8fcdbb6b4e12168304f587999f9d96a421fc80cb933a490df85d25883e6a88750"
"d6bd8b3d4117251eee8f45e70e6daac7dbbd92a9103c623a09355cf00e3f16168"
"e38b9c4cb5b368deabbed8df466bc6835eaba959bc1c2f4ec32a09840becc8b",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1031 = RSAPrivateNumbers(
p=int(
"c0958c08e50137db989fb7cc93abf1984543e2f955d4f43fb2967f40105e79274c852"
- "293fa06ce63ca8436155e475ed6d1f73fea4c8e2516cc79153e3dc83e897", 16),
+ "293fa06ce63ca8436155e475ed6d1f73fea4c8e2516cc79153e3dc83e897",
+ 16,
+ ),
q=int(
"78cae354ea5d6862e5d71d20273b7cddb8cdfab25478fe865180676b04250685c4d03"
- "30c216574f7876a7b12dfe69f1661d3b0cea6c2c0dcfb84050f817afc28d", 16),
+ "30c216574f7876a7b12dfe69f1661d3b0cea6c2c0dcfb84050f817afc28d",
+ 16,
+ ),
d=int(
"1d55cc02b17a5d25bfb39f2bc58389004d0d7255051507f75ef347cdf5519d1a00f4b"
"d235ce4171bfab7bdb7a6dcfae1cf41433fb7da5923cc84f15a675c0b83492c95dd99"
"a9fc157aea352ffdcbb5d59dbc3662171d5838d69f130678ee27841a79ef64f679ce9"
- "3821fa69c03f502244c04b737edad8967def8022a144feaab29", 16),
+ "3821fa69c03f502244c04b737edad8967def8022a144feaab29",
+ 16,
+ ),
dmp1=int(
"5b1c2504ec3a984f86b4414342b5bcf59a0754f13adf25b2a0edbc43f5ba8c3cc061d"
- "80b03e5866d059968f0d10a98deaeb4f7830436d76b22cf41f2914e13eff", 16),
+ "80b03e5866d059968f0d10a98deaeb4f7830436d76b22cf41f2914e13eff",
+ 16,
+ ),
dmq1=int(
"6c361e1819691ab5d67fb2a8f65c958d301cdf24d90617c68ec7005edfb4a7b638cde"
- "79d4b61cfba5c86e8c0ccf296bc7f611cb8d4ae0e072a0f68552ec2d5995", 16),
+ "79d4b61cfba5c86e8c0ccf296bc7f611cb8d4ae0e072a0f68552ec2d5995",
+ 16,
+ ),
iqmp=int(
"b7d61945fdc8b92e075b15554bab507fa8a18edd0a18da373ec6c766c71eece61136a"
- "84b90b6d01741d40458bfad17a9bee9d4a8ed2f6e270782dc3bf5d58b56e", 16),
+ "84b90b6d01741d40458bfad17a9bee9d4a8ed2f6e270782dc3bf5d58b56e",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -437,38 +591,51 @@
"9f73da0690581691626d8a7cf5d972cced9c2091ccf999024b23b4e6dc6d99f80"
"a454737dec0caffaebe4a3fac250ed02079267c8f39620b5ae3e125ca35338522"
"dc9353ecac19cb2fe3b9e3a9291619dbb1ea3a7c388e9ee6469fbf5fb22892b",
- 16),
- )
+ 16,
+ ),
+ ),
)
RSA_KEY_1536 = RSAPrivateNumbers(
p=int(
"f1a65fa4e2aa6e7e2b560251e8a4cd65b625ad9f04f6571785782d1c213d91c961637"
"0c572f2783caf2899f7fb690cf99a0184257fbd4b071b212c88fb348279a5387e61f1"
- "17e9c62980c45ea863fa9292087c0f66ecdcde6443d5a37268bf71", 16),
+ "17e9c62980c45ea863fa9292087c0f66ecdcde6443d5a37268bf71",
+ 16,
+ ),
q=int(
"e54c2cbc3839b1da6ae6fea45038d986d6f523a3ae76051ba20583aab711ea5965cf5"
"3cf54128cc9573f7460bba0fd6758a57aaf240c391790fb38ab473d83ef735510c53d"
- "1d10c31782e8fd7da42615e33565745c30a5e6ceb2a3ae0666cc35", 16),
+ "1d10c31782e8fd7da42615e33565745c30a5e6ceb2a3ae0666cc35",
+ 16,
+ ),
d=int(
"7bcad87e23da2cb2a8c328883fabce06e1f8e9b776c8bf253ad9884e6200e3bd9bd3b"
"a2cbe87d3854527bf005ba5d878c5b0fa20cfb0a2a42884ae95ca12bf7304285e9214"
"5e992f7006c7c0ae839ad550da495b143bec0f4806c7f44caed45f3ccc6dc44cfaf30"
"7abdb757e3d28e41c2d21366835c0a41e50a95af490ac03af061d2feb36ac0afb87be"
"a13fb0f0c5a410727ebedb286c77f9469473fae27ef2c836da6071ef7efc1647f1233"
- "4009a89eecb09a8287abc8c2afd1ddd9a1b0641", 16),
+ "4009a89eecb09a8287abc8c2afd1ddd9a1b0641",
+ 16,
+ ),
dmp1=int(
"a845366cd6f9df1f34861bef7594ed025aa83a12759e245f58adaa9bdff9c3befb760"
"75d3701e90038e888eec9bf092df63400152cb25fc07effc6c74c45f0654ccbde15cd"
- "90dd5504298a946fa5cf22a956072da27a6602e6c6e5c97f2db9c1", 16),
+ "90dd5504298a946fa5cf22a956072da27a6602e6c6e5c97f2db9c1",
+ 16,
+ ),
dmq1=int(
"28b0c1e78cdac03310717992d321a3888830ec6829978c048156152d805b4f8919c61"
"70b5dd204e5ddf3c6c53bc6aff15d0bd09faff7f351b94abb9db980b31f150a6d7573"
- "08eb66938f89a5225cb4dd817a824c89e7a0293b58fc2eefb7e259", 16),
+ "08eb66938f89a5225cb4dd817a824c89e7a0293b58fc2eefb7e259",
+ 16,
+ ),
iqmp=int(
"6c1536c0e16e42a094b6caaf50231ba81916871497d73dcbbbd4bdeb9e60cae0413b3"
"8143b5d680275b29ed7769fe5577e4f9b3647ddb064941120914526d64d80016d2eb7"
- "dc362da7c569623157f3d7cff8347f11494bf5c048d77e28d3f515", 16),
+ "dc362da7c569623157f3d7cff8347f11494bf5c048d77e28d3f515",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -477,8 +644,10 @@
"c248ceef4050160705c188043c8559bf6dbfb6c4bb382eda4e9547575a8227d5b"
"3c0a7088391364cf9f018d8bea053b226ec65e8cdbeaf48a071d0074860a734b1"
"cb7d2146d43014b20776dea42f7853a54690e6cbbf3331a9f43763cfe2a51c329"
- "3bea3b2eebec0d8e43eb317a443afe541107d886e5243c096091543ae65", 16),
- )
+ "3bea3b2eebec0d8e43eb317a443afe541107d886e5243c096091543ae65",
+ 16,
+ ),
+ ),
)
RSA_KEY_2048 = RSAPrivateNumbers(
@@ -486,12 +655,16 @@
"e14202e58c5f7446648d75e5dc465781f661f6b73000c080368afcfb21377f4ef19da"
"845d4ef9bc6b151f6d9f34629103f2e57615f9ba0a3a2fbb035069e1d63b4bb0e78ad"
"dad1ec3c6f87e25c877a1c4c1972098e09158ef7b9bc163852a18d44a70b7b31a03dc"
- "2614fd9ab7bf002cba79054544af3bfbdb6aed06c7b24e6ab", 16),
+ "2614fd9ab7bf002cba79054544af3bfbdb6aed06c7b24e6ab",
+ 16,
+ ),
q=int(
"dbe2bea1ff92599bd19f9d045d6ce62250c05cfeac5117f3cf3e626cb696e3d886379"
"557d5a57b7476f9cf886accfd40508a805fe3b45a78e1a8a125e516cda91640ee6398"
"ec5a39d3e6b177ef12ab00d07907a17640e4ca454fd8487da3c4ffa0d5c2a5edb1221"
- "1c8e33c7ee9fa6753771fd111ec04b8317f86693eb2928c89", 16),
+ "1c8e33c7ee9fa6753771fd111ec04b8317f86693eb2928c89",
+ 16,
+ ),
d=int(
"aef17f80f2653bc30539f26dd4c82ed6abc1d1b53bc0abcdbee47e9a8ab433abde865"
"9fcfae1244d22de6ad333c95aee7d47f30b6815065ac3322744d3ea75058002cd1b29"
@@ -500,22 +673,30 @@
"c8263ce2802a769a090e993fd49abc50c3d3c78c29bee2de0c98055d2f102f1c5684b"
"8dddee611d5205392d8e8dd61a15bf44680972a87f040a611a149271eeb2573f8bf6f"
"627dfa70e77def2ee6584914fa0290e041349ea0999cdff3e493365885b906cbcf195"
- "843345809a85098cca90fea014a21", 16),
+ "843345809a85098cca90fea014a21",
+ 16,
+ ),
dmp1=int(
"9ba56522ffcfa5244eae805c87cc0303461f82be29691b9a7c15a5a050df6c143c575"
"7c288d3d7ab7f32c782e9d9fcddc10a604e6425c0e5d0e46069035d95a923646d276d"
"d9d95b8696fa29ab0de18e53f6f119310f8dd9efca62f0679291166fed8cbd5f18fe1"
- "3a5f1ead1d71d8c90f40382818c18c8d069be793dbc094f69", 16),
+ "3a5f1ead1d71d8c90f40382818c18c8d069be793dbc094f69",
+ 16,
+ ),
dmq1=int(
"a8d4a0aaa2212ccc875796a81353da1fdf00d46676c88d2b96a4bfcdd924622d8e607"
"f3ac1c01dda7ebfb0a97dd7875c2a7b2db6728fb827b89c519f5716fb3228f4121647"
"04b30253c17de2289e9cce3343baa82eb404f789e094a094577a9b0c5314f1725fdf5"
- "8e87611ad20da331bd30b8aebc7dc97d0e9a9ba8579772c9", 16),
+ "8e87611ad20da331bd30b8aebc7dc97d0e9a9ba8579772c9",
+ 16,
+ ),
iqmp=int(
"17bd5ef638c49440d1853acb3fa63a5aca28cb7f94ed350db7001c8445da8943866a7"
"0936e1ee2716c98b484e357cc054d82fbbd98d42f880695d38a1dd4eb096f629b9417"
"aca47e6de5da9f34e60e8a0ffd7e35be74deeef67298d94b3e0db73fc4b7a4cb360c8"
- "9d2117a0bfd9434d37dc7c027d6b01e5295c875015510917d", 16),
+ "9d2117a0bfd9434d37dc7c027d6b01e5295c875015510917d",
+ 16,
+ ),
public_numbers=RSAPublicNumbers(
e=65537,
n=int(
@@ -526,8 +707,10 @@
"c29e53635e24c87a5b2c4215968063cdeb68a972babbc1e3cff00fb9a80e372a4"
"d0c2c920d1e8cee333ce470dc2e8145adb05bf29aee1d24f141e8cc784989c587"
"fc6fbacd979f3f2163c1d7299b365bc72ffe2848e967aed1e48dcc515b3a50ed4"
- "de04fd053846ca10a223b10cc841cc80fdebee44f3114c13e886af583", 16),
- )
+ "de04fd053846ca10a223b10cc841cc80fdebee44f3114c13e886af583",
+ 16,
+ ),
+ ),
)
RSA_KEY_2048_ALT = RSAPrivateNumbers(
@@ -598,6 +781,36 @@
"715070507278514207864914944621214574162116786377990456375"
"964817771730371110612100247262908550409785456157505694419"
"00451152778245269283276012328748538414051025541"
- )
- )
+ ),
+ ),
)
+
+RSA_KEY_CORRUPTED = b"""
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpQIBAAKCAQEAuYE4k09MAsi1yjMrXekMe6sT9bEt3ko47dnmN8YBgO8DiiCc
+226TnQPvuX3FGxU+Y1zTJpcvVL3L37UOvh4CSb9zKyrFK9/x/UcCfK3Eq8JdS98P
+CVeGpkp5E+vwIKY72rc1RSSSCs0PtFdYbSn4trwf5BjPxIqXwIOS3R7zC7cLPHY4
+YdsM4gLGVOP17uXJr/MPoAtWTBVm5zx4bHm6Xclzgf86sbPdL3LxNs0fz4HqJZgA
+6EUtyl6Qypq2LjXbdmm2i3vC+MxW6nEPItPqgComhq0zBmVonsiEO87rEtD548Yq
+DKvxwHhlcODcVkAYebJ+W5L6PPJBNYA3t5wYyQIDAQABAoIBAAbHkg5msftpGt5Z
+Vb3yUuepem7hWTF5YFlIRw5l2wNcURNpbswEhOVNJbuG+KCple7Dw4TuDmhHs/zr
+BRqpDhXldhrUtb2uc3ihqWiVFJbieqE4jUbGvMJusvtXXeDwU6wGWzV/V4qndCrk
+u4PGypk4Cbbq6ZP2oufPryQ3D4Ff1TA06RSWdP3Cg673VqwLtkXwsRDhymAviiqU
+hxQg8bRNiD7mYoUKyLVeV7YRDLTBugfiFmy54yC99NJclLkYmzCgRt1EuoW0Hixx
+EIQFEOLftgpc+sKpbbiOileMsc/stytHXXqfgozhBxDNeSzdNYfwEpkLJpLZSUNV
+EhS4X1cCgYEAz+7DkXksWw9zLqYniMIcvcBnHQcy3Anqbcu8Zbw+I9wOwzNt44Bo
+f88i2idvWvMsRq/LX4WD4jjPB4Z3wAzGBCq+2cy0GrWByMu+VbpwCrntRBkS5huY
+IIf1nr1+BuySNt8TL6nZNKz0D8+5c8wT+VbVdPH//4MzfDrK81PPnesCgYEA5GMy
+ji4l+8zO33LFMlWQGYgfSMd4jGMQD0VCvfhlosK0Py0AfZj/GKEGHduo/37KVVvb
+6XdJqYgB7OxPmdEqbMGeYPKv7pKkG1jXRuEtmXXJ9hS1t0oIvXJLHJnQrOOoRRAR
++xJZbI7WjemY+ZCMOAPT1tm97pxjs81WgSJ6ExsCgYEAze5ADfEeNskkYAz6lnz4
+jgzhkmQwwK+pVzgxy9g8brNkg3qJ2Iix9fKlJ71qkX7IWPF9z4qhxQhSMbfBHZkI
++9OB1J7huJoOgVkXliwIbvcYvxq+Fts5XO6KGb699AmT/XgMvmXO0lbAGLC3kLGL
+DqQrH3kU+m9sLBrmKPrWYiUCgYEA3/8etW4zmMvd1jAFkoFyzGfCbyocZGxAcwm2
+FQYMAN8/03p6sbSd9XTwv9YR4Uxke+WURkjVuW2IneuDgtQv6QCFKob74Jx4Uc4H
+jiAKDioFg9H6C6OUAOKZIpsFnJvIDLxfNkVf6WYKrrL+cz6/F61BVsbGTsGZ094/
+ynWbDyMCgYEAh44C/wkebe0zz/llG+KTRGENsw1c7+pm0/l3wPYAlH02ewbyRjFf
+OKPfyyBtBkoD5rG3IbLyPxsbd3wWwyUzSYq02qRJq43XqyMZhRnNlYhEnNu/Gr5H
+sN1f13zqkKoRxxbIjyh4RDYlAv4Sehk27z2Q3gBe9bI5xKkoQ/VfF2w=
+-----END RSA PRIVATE KEY-----
+"""
diff --git a/tests/hazmat/primitives/test_3des.py b/tests/hazmat/primitives/test_3des.py
index f281ba2..d14dcad 100644
--- a/tests/hazmat/primitives/test_3des.py
+++ b/tests/hazmat/primitives/test_3des.py
@@ -28,7 +28,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestTripleDESModeCBC(object):
- test_KAT = generate_encrypt_test(
+ test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "CBC"),
[
@@ -42,14 +42,10 @@
lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
)
- test_MMT = generate_encrypt_test(
+ test_mmt = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "CBC"),
- [
- "TCBCMMT1.rsp",
- "TCBCMMT2.rsp",
- "TCBCMMT3.rsp",
- ],
+ ["TCBCMMT1.rsp", "TCBCMMT2.rsp", "TCBCMMT3.rsp"],
lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
binascii.unhexlify(key1 + key2 + key3)
),
@@ -65,7 +61,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestTripleDESModeOFB(object):
- test_KAT = generate_encrypt_test(
+ test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "OFB"),
[
@@ -79,14 +75,10 @@
lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)),
)
- test_MMT = generate_encrypt_test(
+ test_mmt = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "OFB"),
- [
- "TOFBMMT1.rsp",
- "TOFBMMT2.rsp",
- "TOFBMMT3.rsp",
- ],
+ ["TOFBMMT1.rsp", "TOFBMMT2.rsp", "TOFBMMT3.rsp"],
lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
binascii.unhexlify(key1 + key2 + key3)
),
@@ -102,7 +94,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestTripleDESModeCFB(object):
- test_KAT = generate_encrypt_test(
+ test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "CFB"),
[
@@ -116,14 +108,10 @@
lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
)
- test_MMT = generate_encrypt_test(
+ test_mmt = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "CFB"),
- [
- "TCFB64MMT1.rsp",
- "TCFB64MMT2.rsp",
- "TCFB64MMT3.rsp",
- ],
+ ["TCFB64MMT1.rsp", "TCFB64MMT2.rsp", "TCFB64MMT3.rsp"],
lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
binascii.unhexlify(key1 + key2 + key3)
),
@@ -139,7 +127,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestTripleDESModeCFB8(object):
- test_KAT = generate_encrypt_test(
+ test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "CFB"),
[
@@ -153,14 +141,10 @@
lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)),
)
- test_MMT = generate_encrypt_test(
+ test_mmt = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "CFB"),
- [
- "TCFB8MMT1.rsp",
- "TCFB8MMT2.rsp",
- "TCFB8MMT3.rsp",
- ],
+ ["TCFB8MMT1.rsp", "TCFB8MMT2.rsp", "TCFB8MMT3.rsp"],
lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
binascii.unhexlify(key1 + key2 + key3)
),
@@ -176,7 +160,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestTripleDESModeECB(object):
- test_KAT = generate_encrypt_test(
+ test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "ECB"),
[
@@ -190,14 +174,10 @@
lambda **kwargs: modes.ECB(),
)
- test_MMT = generate_encrypt_test(
+ test_mmt = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "ECB"),
- [
- "TECBMMT1.rsp",
- "TECBMMT2.rsp",
- "TECBMMT3.rsp",
- ],
+ ["TECBMMT1.rsp", "TECBMMT2.rsp", "TECBMMT3.rsp"],
lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
binascii.unhexlify(key1 + key2 + key3)
),
diff --git a/tests/hazmat/primitives/test_aead.py b/tests/hazmat/primitives/test_aead.py
index e1a17a9..2706931 100644
--- a/tests/hazmat/primitives/test_aead.py
+++ b/tests/hazmat/primitives/test_aead.py
@@ -12,13 +12,17 @@
from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.backends.interfaces import CipherBackend
from cryptography.hazmat.primitives.ciphers.aead import (
- AESCCM, AESGCM, ChaCha20Poly1305
+ AESCCM,
+ AESGCM,
+ ChaCha20Poly1305,
)
from .utils import _load_all_params
from ...utils import (
- load_nist_ccm_vectors, load_nist_vectors, load_vectors_from_file,
- raises_unsupported_algorithm
+ load_nist_ccm_vectors,
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
@@ -37,7 +41,7 @@
@pytest.mark.skipif(
_aead_supported(ChaCha20Poly1305),
- reason="Requires OpenSSL without ChaCha20Poly1305 support"
+ reason="Requires OpenSSL without ChaCha20Poly1305 support",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
def test_chacha20poly1305_unsupported_on_older_openssl(backend):
@@ -47,7 +51,7 @@
@pytest.mark.skipif(
not _aead_supported(ChaCha20Poly1305),
- reason="Does not support ChaCha20Poly1305"
+ reason="Does not support ChaCha20Poly1305",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestChaCha20Poly1305(object):
@@ -78,11 +82,12 @@
[
[object(), b"data", b""],
[b"0" * 12, object(), b""],
- [b"0" * 12, b"data", object()]
- ]
+ [b"0" * 12, b"data", object()],
+ ],
)
- def test_params_not_bytes_encrypt(self, nonce, data, associated_data,
- backend):
+ def test_params_not_bytes_encrypt(
+ self, nonce, data, associated_data, backend
+ ):
key = ChaCha20Poly1305.generate_key()
chacha = ChaCha20Poly1305(key)
with pytest.raises(TypeError):
@@ -121,8 +126,8 @@
"vector",
load_vectors_from_file(
os.path.join("ciphers", "ChaCha20Poly1305", "openssl.txt"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_openssl_vectors(self, vector, backend):
key = binascii.unhexlify(vector["key"])
@@ -145,8 +150,8 @@
"vector",
load_vectors_from_file(
os.path.join("ciphers", "ChaCha20Poly1305", "boringssl.txt"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_boringssl_vectors(self, vector, backend):
key = binascii.unhexlify(vector["key"])
@@ -183,20 +188,6 @@
assert computed_pt2 == pt
-@pytest.mark.skipif(
- _aead_supported(AESCCM),
- reason="Requires OpenSSL without AES-CCM support"
-)
-@pytest.mark.requires_backend_interface(interface=CipherBackend)
-def test_aesccm_unsupported_on_older_openssl(backend):
- with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
- AESCCM(AESCCM.generate_key(128))
-
-
-@pytest.mark.skipif(
- not _aead_supported(AESCCM),
- reason="Does not support AESCCM"
-)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESCCM(object):
def test_data_too_large(self):
@@ -245,22 +236,30 @@
_load_all_params(
os.path.join("ciphers", "AES", "CCM"),
[
- "DVPT128.rsp", "DVPT192.rsp", "DVPT256.rsp",
- "VADT128.rsp", "VADT192.rsp", "VADT256.rsp",
- "VNT128.rsp", "VNT192.rsp", "VNT256.rsp",
- "VPT128.rsp", "VPT192.rsp", "VPT256.rsp",
+ "DVPT128.rsp",
+ "DVPT192.rsp",
+ "DVPT256.rsp",
+ "VADT128.rsp",
+ "VADT192.rsp",
+ "VADT256.rsp",
+ "VNT128.rsp",
+ "VNT192.rsp",
+ "VNT256.rsp",
+ "VPT128.rsp",
+ "VPT192.rsp",
+ "VPT256.rsp",
],
- load_nist_ccm_vectors
- )
+ load_nist_ccm_vectors,
+ ),
)
def test_vectors(self, vector, backend):
key = binascii.unhexlify(vector["key"])
nonce = binascii.unhexlify(vector["nonce"])
- adata = binascii.unhexlify(vector["adata"])[:vector["alen"]]
+ adata = binascii.unhexlify(vector["adata"])[: vector["alen"]]
ct = binascii.unhexlify(vector["ct"])
- pt = binascii.unhexlify(vector["payload"])[:vector["plen"]]
+ pt = binascii.unhexlify(vector["payload"])[: vector["plen"]]
aesccm = AESCCM(key, vector["tlen"])
- if vector.get('fail'):
+ if vector.get("fail"):
with pytest.raises(InvalidTag):
aesccm.decrypt(nonce, ct, adata)
else:
@@ -293,7 +292,7 @@
[object(), b"data", b""],
[b"0" * 12, object(), b""],
[b"0" * 12, b"data", object()],
- ]
+ ],
)
def test_params_not_bytes(self, nonce, data, associated_data, backend):
key = AESCCM.generate_key(128)
@@ -359,7 +358,7 @@
"gcmEncryptExtIV192.rsp",
"gcmEncryptExtIV256.rsp",
],
- load_nist_vectors
+ load_nist_vectors,
)
return [x for x in vectors if len(x["tag"]) == 32]
@@ -378,9 +377,18 @@
aesgcm.encrypt(nonce, b"", FakeData())
@pytest.mark.parametrize("vector", _load_gcm_vectors())
- def test_vectors(self, vector):
- key = binascii.unhexlify(vector["key"])
+ def test_vectors(self, backend, vector):
nonce = binascii.unhexlify(vector["iv"])
+
+ if len(nonce) < 8:
+ pytest.skip("GCM does not support less than 64-bit IVs")
+
+ if backend._fips_enabled and len(nonce) != 12:
+ # Red Hat disables non-96-bit IV support as part of its FIPS
+ # patches.
+ pytest.skip("Non-96-bit IVs unsupported in FIPS mode.")
+
+ key = binascii.unhexlify(vector["key"])
aad = binascii.unhexlify(vector["aad"])
ct = binascii.unhexlify(vector["ct"])
pt = binascii.unhexlify(vector.get("pt", b""))
@@ -401,8 +409,8 @@
[
[object(), b"data", b""],
[b"0" * 12, object(), b""],
- [b"0" * 12, b"data", object()]
- ]
+ [b"0" * 12, b"data", object()],
+ ],
)
def test_params_not_bytes(self, nonce, data, associated_data, backend):
key = AESGCM.generate_key(128)
@@ -413,11 +421,17 @@
with pytest.raises(TypeError):
aesgcm.decrypt(nonce, data, associated_data)
- def test_invalid_nonce_length(self, backend):
+ @pytest.mark.parametrize("length", [7, 129])
+ def test_invalid_nonce_length(self, length, backend):
+ if backend._fips_enabled:
+ # Red Hat disables non-96-bit IV support as part of its FIPS
+ # patches.
+ pytest.skip("Non-96-bit IVs unsupported in FIPS mode.")
+
key = AESGCM.generate_key(128)
aesgcm = AESGCM(key)
with pytest.raises(ValueError):
- aesgcm.encrypt(b"", b"hi", None)
+ aesgcm.encrypt(b"\x00" * length, b"hi", None)
def test_bad_key(self, backend):
with pytest.raises(TypeError):
diff --git a/tests/hazmat/primitives/test_aes.py b/tests/hazmat/primitives/test_aes.py
index 90a6b3b..f98ba6f 100644
--- a/tests/hazmat/primitives/test_aes.py
+++ b/tests/hazmat/primitives/test_aes.py
@@ -12,7 +12,8 @@
from cryptography.hazmat.backends.interfaces import CipherBackend
from cryptography.hazmat.primitives.ciphers import algorithms, base, modes
-from .utils import _load_all_params, generate_aead_test, generate_encrypt_test
+from .utils import _load_all_params, generate_encrypt_test
+from ...doubles import DummyMode
from ...utils import load_nist_vectors
@@ -30,11 +31,15 @@
# data unit length that is divisible by 8. The NIST vectors include
# tests for implementations that support encryption of data that is
# not divisible modulo 8, but OpenSSL is not such an implementation.
- [x for x in _load_all_params(
- os.path.join("ciphers", "AES", "XTS", "tweak-128hexstr"),
- ["XTSGenAES128.rsp", "XTSGenAES256.rsp"],
- load_nist_vectors
- ) if int(x["dataunitlen"]) / 8.0 == int(x["dataunitlen"]) // 8]
+ [
+ x
+ for x in _load_all_params(
+ os.path.join("ciphers", "AES", "XTS", "tweak-128hexstr"),
+ ["XTSGenAES128.rsp", "XTSGenAES256.rsp"],
+ load_nist_vectors,
+ )
+ if int(x["dataunitlen"]) / 8.0 == int(x["dataunitlen"]) // 8
+ ],
)
def test_xts_vectors(self, vector, backend):
key = binascii.unhexlify(vector["key"])
@@ -58,7 +63,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESModeCBC(object):
- test_CBC = generate_encrypt_test(
+ test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "CBC"),
[
@@ -91,7 +96,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESModeECB(object):
- test_ECB = generate_encrypt_test(
+ test_ecb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "ECB"),
[
@@ -124,7 +129,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESModeOFB(object):
- test_OFB = generate_encrypt_test(
+ test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "OFB"),
[
@@ -157,7 +162,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESModeCFB(object):
- test_CFB = generate_encrypt_test(
+ test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "CFB"),
[
@@ -190,7 +195,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESModeCFB8(object):
- test_CFB8 = generate_encrypt_test(
+ test_cfb8 = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "CFB"),
[
@@ -223,7 +228,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESModeCTR(object):
- test_CTR = generate_encrypt_test(
+ test_ctr = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "CTR"),
["aes-128-ctr.txt", "aes-192-ctr.txt", "aes-256-ctr.txt"],
@@ -232,249 +237,6 @@
)
-@pytest.mark.supported(
- only_if=lambda backend: backend.cipher_supported(
- algorithms.AES(b"\x00" * 16), modes.GCM(b"\x00" * 12)
- ),
- skip_message="Does not support AES GCM",
-)
-@pytest.mark.requires_backend_interface(interface=CipherBackend)
-class TestAESModeGCM(object):
- test_GCM = generate_aead_test(
- load_nist_vectors,
- os.path.join("ciphers", "AES", "GCM"),
- [
- "gcmDecrypt128.rsp",
- "gcmDecrypt192.rsp",
- "gcmDecrypt256.rsp",
- "gcmEncryptExtIV128.rsp",
- "gcmEncryptExtIV192.rsp",
- "gcmEncryptExtIV256.rsp",
- ],
- algorithms.AES,
- modes.GCM,
- )
-
- def test_gcm_tag_with_only_aad(self, backend):
- key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
- iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
- aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
- tag = binascii.unhexlify(b"0f247e7f9c2505de374006738018493b")
-
- cipher = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- )
- encryptor = cipher.encryptor()
- encryptor.authenticate_additional_data(aad)
- encryptor.finalize()
- assert encryptor.tag == tag
-
- def test_gcm_ciphertext_with_no_aad(self, backend):
- key = binascii.unhexlify(b"e98b72a9881a84ca6b76e0f43e68647a")
- iv = binascii.unhexlify(b"8b23299fde174053f3d652ba")
- ct = binascii.unhexlify(b"5a3c1cf1985dbb8bed818036fdd5ab42")
- tag = binascii.unhexlify(b"23c7ab0f952b7091cd324835043b5eb5")
- pt = binascii.unhexlify(b"28286a321293253c3e0aa2704a278032")
-
- cipher = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- )
- encryptor = cipher.encryptor()
- computed_ct = encryptor.update(pt) + encryptor.finalize()
- assert computed_ct == ct
- assert encryptor.tag == tag
-
- def test_gcm_ciphertext_limit(self, backend):
- encryptor = base.Cipher(
- algorithms.AES(b"\x00" * 16),
- modes.GCM(b"\x01" * 16),
- backend=backend
- ).encryptor()
- encryptor._bytes_processed = modes.GCM._MAX_ENCRYPTED_BYTES - 16
- encryptor.update(b"0" * 16)
- assert (
- encryptor._bytes_processed == modes.GCM._MAX_ENCRYPTED_BYTES
- )
- with pytest.raises(ValueError):
- encryptor.update(b"0")
-
- def test_gcm_aad_limit(self, backend):
- encryptor = base.Cipher(
- algorithms.AES(b"\x00" * 16),
- modes.GCM(b"\x01" * 16),
- backend=backend
- ).encryptor()
- encryptor._aad_bytes_processed = modes.GCM._MAX_AAD_BYTES - 16
- encryptor.authenticate_additional_data(b"0" * 16)
- assert encryptor._aad_bytes_processed == modes.GCM._MAX_AAD_BYTES
- with pytest.raises(ValueError):
- encryptor.authenticate_additional_data(b"0")
-
- def test_gcm_ciphertext_increments(self, backend):
- encryptor = base.Cipher(
- algorithms.AES(b"\x00" * 16),
- modes.GCM(b"\x01" * 16),
- backend=backend
- ).encryptor()
- encryptor.update(b"0" * 8)
- assert encryptor._bytes_processed == 8
- encryptor.update(b"0" * 7)
- assert encryptor._bytes_processed == 15
- encryptor.update(b"0" * 18)
- assert encryptor._bytes_processed == 33
-
- def test_gcm_aad_increments(self, backend):
- encryptor = base.Cipher(
- algorithms.AES(b"\x00" * 16),
- modes.GCM(b"\x01" * 16),
- backend=backend
- ).encryptor()
- encryptor.authenticate_additional_data(b"0" * 8)
- assert encryptor._aad_bytes_processed == 8
- encryptor.authenticate_additional_data(b"0" * 18)
- assert encryptor._aad_bytes_processed == 26
-
- def test_gcm_tag_decrypt_none(self, backend):
- key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
- iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
- aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
-
- encryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- ).encryptor()
- encryptor.authenticate_additional_data(aad)
- encryptor.finalize()
-
- if (
- backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_102 and
- not backend._lib.CRYPTOGRAPHY_IS_LIBRESSL
- ):
- with pytest.raises(NotImplementedError):
- decryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- ).decryptor()
- else:
- decryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- ).decryptor()
- decryptor.authenticate_additional_data(aad)
- with pytest.raises(ValueError):
- decryptor.finalize()
-
- def test_gcm_tag_decrypt_mode(self, backend):
- key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
- iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
- aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
-
- encryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- ).encryptor()
- encryptor.authenticate_additional_data(aad)
- encryptor.finalize()
- tag = encryptor.tag
-
- decryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv, tag),
- backend=backend
- ).decryptor()
- decryptor.authenticate_additional_data(aad)
- decryptor.finalize()
-
- def test_gcm_tag_decrypt_finalize(self, backend):
- key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
- iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
- aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
-
- encryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- ).encryptor()
- encryptor.authenticate_additional_data(aad)
- encryptor.finalize()
- tag = encryptor.tag
-
- if (
- backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_102 and
- not backend._lib.CRYPTOGRAPHY_IS_LIBRESSL
- ):
- with pytest.raises(NotImplementedError):
- decryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- ).decryptor()
- decryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv, tag=encryptor.tag),
- backend=backend
- ).decryptor()
- else:
- decryptor = base.Cipher(
- algorithms.AES(key),
- modes.GCM(iv),
- backend=backend
- ).decryptor()
- decryptor.authenticate_additional_data(aad)
-
- if (
- backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_102 and
- not backend._lib.CRYPTOGRAPHY_IS_LIBRESSL
- ):
- with pytest.raises(NotImplementedError):
- decryptor.finalize_with_tag(tag)
- decryptor.finalize()
- else:
- decryptor.finalize_with_tag(tag)
-
- @pytest.mark.supported(
- only_if=lambda backend: (
- not backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_102 or
- backend._lib.CRYPTOGRAPHY_IS_LIBRESSL
- ),
- skip_message="Not supported on OpenSSL 1.0.1",
- )
- def test_gcm_tag_decrypt_finalize_tag_length(self, backend):
- decryptor = base.Cipher(
- algorithms.AES(b"0" * 16),
- modes.GCM(b"0" * 12),
- backend=backend
- ).decryptor()
- with pytest.raises(ValueError):
- decryptor.finalize_with_tag(b"tagtooshort")
-
- def test_buffer_protocol(self, backend):
- data = bytearray(b"helloworld")
- enc = base.Cipher(
- algorithms.AES(bytearray(b"\x00" * 16)),
- modes.GCM(bytearray(b"\x00" * 12)),
- backend
- ).encryptor()
- enc.authenticate_additional_data(bytearray(b"foo"))
- ct = enc.update(data) + enc.finalize()
- dec = base.Cipher(
- algorithms.AES(bytearray(b"\x00" * 16)),
- modes.GCM(bytearray(b"\x00" * 12), enc.tag),
- backend
- ).decryptor()
- dec.authenticate_additional_data(bytearray(b"foo"))
- pt = dec.update(ct) + dec.finalize()
- assert pt == data
-
-
@pytest.mark.parametrize(
"mode",
[
@@ -484,14 +246,17 @@
modes.CFB(bytearray(b"\x00" * 16)),
modes.CFB8(bytearray(b"\x00" * 16)),
modes.XTS(bytearray(b"\x00" * 16)),
- ]
+ # Add a dummy mode for coverage of the cipher_supported check.
+ DummyMode(),
+ ],
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
def test_buffer_protocol_alternate_modes(mode, backend):
data = bytearray(b"sixteen_byte_msg")
- cipher = base.Cipher(
- algorithms.AES(bytearray(b"\x00" * 32)), mode, backend
- )
+ key = algorithms.AES(bytearray(os.urandom(32)))
+ if not backend.cipher_supported(key, mode):
+ pytest.skip("AES in {} mode not supported".format(mode.name))
+ cipher = base.Cipher(key, mode, backend)
enc = cipher.encryptor()
ct = enc.update(data) + enc.finalize()
dec = cipher.decryptor()
diff --git a/tests/hazmat/primitives/test_aes_gcm.py b/tests/hazmat/primitives/test_aes_gcm.py
new file mode 100644
index 0000000..8b71d12
--- /dev/null
+++ b/tests/hazmat/primitives/test_aes_gcm.py
@@ -0,0 +1,219 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from __future__ import absolute_import, division, print_function
+
+import binascii
+import os
+
+import pytest
+
+from cryptography.hazmat.backends.interfaces import CipherBackend
+from cryptography.hazmat.primitives.ciphers import algorithms, base, modes
+
+from .utils import generate_aead_test
+from ...utils import load_nist_vectors
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: backend.cipher_supported(
+ algorithms.AES(b"\x00" * 16), modes.GCM(b"\x00" * 12)
+ ),
+ skip_message="Does not support AES GCM",
+)
+@pytest.mark.requires_backend_interface(interface=CipherBackend)
+class TestAESModeGCM(object):
+ test_gcm = generate_aead_test(
+ load_nist_vectors,
+ os.path.join("ciphers", "AES", "GCM"),
+ [
+ "gcmDecrypt128.rsp",
+ "gcmDecrypt192.rsp",
+ "gcmDecrypt256.rsp",
+ "gcmEncryptExtIV128.rsp",
+ "gcmEncryptExtIV192.rsp",
+ "gcmEncryptExtIV256.rsp",
+ ],
+ algorithms.AES,
+ modes.GCM,
+ )
+
+ def test_gcm_tag_with_only_aad(self, backend):
+ key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
+ iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
+ aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
+ tag = binascii.unhexlify(b"0f247e7f9c2505de374006738018493b")
+
+ cipher = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv), backend=backend
+ )
+ encryptor = cipher.encryptor()
+ encryptor.authenticate_additional_data(aad)
+ encryptor.finalize()
+ assert encryptor.tag == tag
+
+ def test_gcm_ciphertext_with_no_aad(self, backend):
+ key = binascii.unhexlify(b"e98b72a9881a84ca6b76e0f43e68647a")
+ iv = binascii.unhexlify(b"8b23299fde174053f3d652ba")
+ ct = binascii.unhexlify(b"5a3c1cf1985dbb8bed818036fdd5ab42")
+ tag = binascii.unhexlify(b"23c7ab0f952b7091cd324835043b5eb5")
+ pt = binascii.unhexlify(b"28286a321293253c3e0aa2704a278032")
+
+ cipher = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv), backend=backend
+ )
+ encryptor = cipher.encryptor()
+ computed_ct = encryptor.update(pt) + encryptor.finalize()
+ assert computed_ct == ct
+ assert encryptor.tag == tag
+
+ def test_gcm_ciphertext_limit(self, backend):
+ encryptor = base.Cipher(
+ algorithms.AES(b"\x00" * 16),
+ modes.GCM(b"\x01" * 16),
+ backend=backend,
+ ).encryptor()
+ encryptor._bytes_processed = modes.GCM._MAX_ENCRYPTED_BYTES - 16
+ encryptor.update(b"0" * 16)
+ assert encryptor._bytes_processed == modes.GCM._MAX_ENCRYPTED_BYTES
+ with pytest.raises(ValueError):
+ encryptor.update(b"0")
+
+ def test_gcm_aad_limit(self, backend):
+ encryptor = base.Cipher(
+ algorithms.AES(b"\x00" * 16),
+ modes.GCM(b"\x01" * 16),
+ backend=backend,
+ ).encryptor()
+ encryptor._aad_bytes_processed = modes.GCM._MAX_AAD_BYTES - 16
+ encryptor.authenticate_additional_data(b"0" * 16)
+ assert encryptor._aad_bytes_processed == modes.GCM._MAX_AAD_BYTES
+ with pytest.raises(ValueError):
+ encryptor.authenticate_additional_data(b"0")
+
+ def test_gcm_ciphertext_increments(self, backend):
+ encryptor = base.Cipher(
+ algorithms.AES(b"\x00" * 16),
+ modes.GCM(b"\x01" * 16),
+ backend=backend,
+ ).encryptor()
+ encryptor.update(b"0" * 8)
+ assert encryptor._bytes_processed == 8
+ encryptor.update(b"0" * 7)
+ assert encryptor._bytes_processed == 15
+ encryptor.update(b"0" * 18)
+ assert encryptor._bytes_processed == 33
+
+ def test_gcm_aad_increments(self, backend):
+ encryptor = base.Cipher(
+ algorithms.AES(b"\x00" * 16),
+ modes.GCM(b"\x01" * 16),
+ backend=backend,
+ ).encryptor()
+ encryptor.authenticate_additional_data(b"0" * 8)
+ assert encryptor._aad_bytes_processed == 8
+ encryptor.authenticate_additional_data(b"0" * 18)
+ assert encryptor._aad_bytes_processed == 26
+
+ def test_gcm_tag_decrypt_none(self, backend):
+ key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
+ iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
+ aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
+
+ encryptor = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv), backend=backend
+ ).encryptor()
+ encryptor.authenticate_additional_data(aad)
+ encryptor.finalize()
+
+ decryptor = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv), backend=backend
+ ).decryptor()
+ decryptor.authenticate_additional_data(aad)
+ with pytest.raises(ValueError):
+ decryptor.finalize()
+
+ def test_gcm_tag_decrypt_mode(self, backend):
+ key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
+ iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
+ aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
+
+ encryptor = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv), backend=backend
+ ).encryptor()
+ encryptor.authenticate_additional_data(aad)
+ encryptor.finalize()
+ tag = encryptor.tag
+
+ decryptor = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv, tag), backend=backend
+ ).decryptor()
+ decryptor.authenticate_additional_data(aad)
+ decryptor.finalize()
+
+ def test_gcm_tag_decrypt_finalize(self, backend):
+ key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3")
+ iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d")
+ aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193")
+
+ encryptor = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv), backend=backend
+ ).encryptor()
+ encryptor.authenticate_additional_data(aad)
+ encryptor.finalize()
+ tag = encryptor.tag
+
+ decryptor = base.Cipher(
+ algorithms.AES(key), modes.GCM(iv), backend=backend
+ ).decryptor()
+ decryptor.authenticate_additional_data(aad)
+
+ decryptor.finalize_with_tag(tag)
+
+ def test_gcm_tag_decrypt_finalize_tag_length(self, backend):
+ decryptor = base.Cipher(
+ algorithms.AES(b"0" * 16), modes.GCM(b"0" * 12), backend=backend
+ ).decryptor()
+ with pytest.raises(ValueError):
+ decryptor.finalize_with_tag(b"tagtooshort")
+
+ def test_buffer_protocol(self, backend):
+ data = bytearray(b"helloworld")
+ enc = base.Cipher(
+ algorithms.AES(bytearray(b"\x00" * 16)),
+ modes.GCM(bytearray(b"\x00" * 12)),
+ backend,
+ ).encryptor()
+ enc.authenticate_additional_data(bytearray(b"foo"))
+ ct = enc.update(data) + enc.finalize()
+ dec = base.Cipher(
+ algorithms.AES(bytearray(b"\x00" * 16)),
+ modes.GCM(bytearray(b"\x00" * 12), enc.tag),
+ backend,
+ ).decryptor()
+ dec.authenticate_additional_data(bytearray(b"foo"))
+ pt = dec.update(ct) + dec.finalize()
+ assert pt == data
+
+ @pytest.mark.parametrize("size", [8, 128])
+ def test_gcm_min_max_iv(self, size, backend):
+ if backend._fips_enabled:
+ # Red Hat disables non-96-bit IV support as part of its FIPS
+ # patches.
+ pytest.skip("Non-96-bit IVs unsupported in FIPS mode.")
+
+ key = os.urandom(16)
+ iv = b"\x00" * size
+
+ payload = b"data"
+ encryptor = base.Cipher(algorithms.AES(key), modes.GCM(iv)).encryptor()
+ ct = encryptor.update(payload)
+ encryptor.finalize()
+ tag = encryptor.tag
+
+ decryptor = base.Cipher(algorithms.AES(key), modes.GCM(iv)).decryptor()
+ pt = decryptor.update(ct)
+
+ decryptor.finalize_with_tag(tag)
+ assert pt == payload
diff --git a/tests/hazmat/primitives/test_arc4.py b/tests/hazmat/primitives/test_arc4.py
index 1a17344..de20b70 100644
--- a/tests/hazmat/primitives/test_arc4.py
+++ b/tests/hazmat/primitives/test_arc4.py
@@ -35,7 +35,7 @@
"rfc-6229-128.txt",
"rfc-6229-192.txt",
"rfc-6229-256.txt",
- "arc4.txt"
+ "arc4.txt",
],
lambda key, **kwargs: algorithms.ARC4(binascii.unhexlify(key)),
)
diff --git a/tests/hazmat/primitives/test_asym_utils.py b/tests/hazmat/primitives/test_asym_utils.py
index fc9e9fd..70bff01 100644
--- a/tests/hazmat/primitives/test_asym_utils.py
+++ b/tests/hazmat/primitives/test_asym_utils.py
@@ -7,19 +7,10 @@
import pytest
from cryptography.hazmat.primitives.asymmetric.utils import (
- Prehashed, decode_dss_signature, decode_rfc6979_signature,
- encode_dss_signature, encode_rfc6979_signature,
+ Prehashed,
+ decode_dss_signature,
+ encode_dss_signature,
)
-from cryptography.utils import CryptographyDeprecationWarning
-
-
-def test_deprecated_rfc6979_signature():
- with pytest.warns(CryptographyDeprecationWarning):
- sig = encode_rfc6979_signature(1, 1)
- assert sig == b"0\x06\x02\x01\x01\x02\x01\x01"
- with pytest.warns(CryptographyDeprecationWarning):
- decoded = decode_rfc6979_signature(sig)
- assert decoded == (1, 1)
def test_dss_signature():
@@ -29,11 +20,11 @@
r_s1 = (
1037234182290683143945502320610861668562885151617,
- 559776156650501990899426031439030258256861634312
+ 559776156650501990899426031439030258256861634312,
)
sig2 = encode_dss_signature(*r_s1)
assert sig2 == (
- b'0-\x02\x15\x00\xb5\xaf0xg\xfb\x8bT9\x00\x13\xccg\x02\r\xdf\x1f,\x0b'
+ b"0-\x02\x15\x00\xb5\xaf0xg\xfb\x8bT9\x00\x13\xccg\x02\r\xdf\x1f,\x0b"
b'\x81\x02\x14b\r;"\xabP1D\x0c>5\xea\xb6\xf4\x81)\x8f\x9e\x9f\x08'
)
assert decode_dss_signature(sig2) == r_s1
@@ -42,10 +33,6 @@
assert sig3 == b"0\x06\x02\x01\x00\x02\x01\x00"
assert decode_dss_signature(sig3) == (0, 0)
- sig4 = encode_dss_signature(-1, 0)
- assert sig4 == b"0\x06\x02\x01\xFF\x02\x01\x00"
- assert decode_dss_signature(sig4) == (-1, 0)
-
def test_encode_dss_non_integer():
with pytest.raises(ValueError):
@@ -64,6 +51,11 @@
encode_dss_signature("hello", "world")
+def test_encode_dss_negative():
+ with pytest.raises(ValueError):
+ encode_dss_signature(-1, 0)
+
+
def test_decode_dss_trailing_bytes():
with pytest.raises(ValueError):
decode_dss_signature(b"0\x06\x02\x01\x01\x02\x01\x01\x00\x00\x00")
diff --git a/tests/hazmat/primitives/test_block.py b/tests/hazmat/primitives/test_block.py
index 37158f1..5931993 100644
--- a/tests/hazmat/primitives/test_block.py
+++ b/tests/hazmat/primitives/test_block.py
@@ -8,16 +8,18 @@
import pytest
-from cryptography.exceptions import (
- AlreadyFinalized, _Reasons
-)
+from cryptography.exceptions import AlreadyFinalized, _Reasons
from cryptography.hazmat.backends.interfaces import CipherBackend
from cryptography.hazmat.primitives.ciphers import (
- Cipher, algorithms, base, modes
+ Cipher,
+ algorithms,
+ base,
+ modes,
)
from .utils import (
- generate_aead_exception_test, generate_aead_tag_exception_test
+ generate_aead_exception_test,
+ generate_aead_tag_exception_test,
)
from ...doubles import DummyCipherAlgorithm, DummyMode
from ...utils import raises_unsupported_algorithm
@@ -29,7 +31,7 @@
cipher = Cipher(
algorithms.AES(binascii.unhexlify(b"0" * 32)),
modes.CBC(binascii.unhexlify(b"0" * 32)),
- backend
+ backend,
)
assert isinstance(cipher.encryptor(), base.CipherContext)
@@ -37,7 +39,7 @@
cipher = Cipher(
algorithms.AES(binascii.unhexlify(b"0" * 32)),
modes.CBC(binascii.unhexlify(b"0" * 32)),
- backend
+ backend,
)
assert isinstance(cipher.decryptor(), base.CipherContext)
@@ -53,7 +55,7 @@
cipher = Cipher(
algorithms.AES(binascii.unhexlify(b"0" * 32)),
modes.CBC(binascii.unhexlify(b"0" * 32)),
- backend
+ backend,
)
encryptor = cipher.encryptor()
encryptor.update(b"a" * 16)
@@ -74,7 +76,7 @@
cipher = Cipher(
algorithms.AES(binascii.unhexlify(b"0" * 32)),
modes.CBC(binascii.unhexlify(b"0" * 32)),
- backend
+ backend,
)
encryptor = cipher.encryptor()
encryptor.update(b"a" * 16)
@@ -85,9 +87,7 @@
def test_unaligned_block_encryption(self, backend):
cipher = Cipher(
- algorithms.AES(binascii.unhexlify(b"0" * 32)),
- modes.ECB(),
- backend
+ algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.ECB(), backend
)
encryptor = cipher.encryptor()
ct = encryptor.update(b"a" * 15)
@@ -105,9 +105,7 @@
@pytest.mark.parametrize("mode", [DummyMode(), None])
def test_nonexistent_cipher(self, backend, mode):
- cipher = Cipher(
- DummyCipherAlgorithm(), mode, backend
- )
+ cipher = Cipher(DummyCipherAlgorithm(), mode, backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
cipher.encryptor()
@@ -116,9 +114,7 @@
def test_incorrectly_padded(self, backend):
cipher = Cipher(
- algorithms.AES(b"\x00" * 16),
- modes.CBC(b"\x00" * 16),
- backend
+ algorithms.AES(b"\x00" * 16), modes.CBC(b"\x00" * 16), backend
)
encryptor = cipher.encryptor()
encryptor.update(b"1")
diff --git a/tests/hazmat/primitives/test_blowfish.py b/tests/hazmat/primitives/test_blowfish.py
index 0c38b98..5f7480e 100644
--- a/tests/hazmat/primitives/test_blowfish.py
+++ b/tests/hazmat/primitives/test_blowfish.py
@@ -24,7 +24,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestBlowfishModeECB(object):
- test_ECB = generate_encrypt_test(
+ test_ecb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Blowfish"),
["bf-ecb.txt"],
@@ -41,7 +41,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestBlowfishModeCBC(object):
- test_CBC = generate_encrypt_test(
+ test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Blowfish"),
["bf-cbc.txt"],
@@ -58,7 +58,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestBlowfishModeOFB(object):
- test_OFB = generate_encrypt_test(
+ test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Blowfish"),
["bf-ofb.txt"],
@@ -75,7 +75,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestBlowfishModeCFB(object):
- test_CFB = generate_encrypt_test(
+ test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Blowfish"),
["bf-cfb.txt"],
diff --git a/tests/hazmat/primitives/test_camellia.py b/tests/hazmat/primitives/test_camellia.py
index 87fcfe3..b752345 100644
--- a/tests/hazmat/primitives/test_camellia.py
+++ b/tests/hazmat/primitives/test_camellia.py
@@ -13,9 +13,7 @@
from cryptography.hazmat.primitives.ciphers import algorithms, modes
from .utils import generate_encrypt_test
-from ...utils import (
- load_cryptrec_vectors, load_nist_vectors
-)
+from ...utils import load_cryptrec_vectors, load_nist_vectors
@pytest.mark.supported(
@@ -26,13 +24,13 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCamelliaModeECB(object):
- test_ECB = generate_encrypt_test(
+ test_ecb = generate_encrypt_test(
load_cryptrec_vectors,
os.path.join("ciphers", "Camellia"),
[
"camellia-128-ecb.txt",
"camellia-192-ecb.txt",
- "camellia-256-ecb.txt"
+ "camellia-256-ecb.txt",
],
lambda key, **kwargs: algorithms.Camellia(binascii.unhexlify(key)),
lambda **kwargs: modes.ECB(),
@@ -47,7 +45,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCamelliaModeCBC(object):
- test_CBC = generate_encrypt_test(
+ test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Camellia"),
["camellia-cbc.txt"],
@@ -64,7 +62,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCamelliaModeOFB(object):
- test_OFB = generate_encrypt_test(
+ test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Camellia"),
["camellia-ofb.txt"],
@@ -81,7 +79,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCamelliaModeCFB(object):
- test_CFB = generate_encrypt_test(
+ test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Camellia"),
["camellia-cfb.txt"],
diff --git a/tests/hazmat/primitives/test_cast5.py b/tests/hazmat/primitives/test_cast5.py
index ec51659..eff5d25 100644
--- a/tests/hazmat/primitives/test_cast5.py
+++ b/tests/hazmat/primitives/test_cast5.py
@@ -24,7 +24,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCAST5ModeECB(object):
- test_ECB = generate_encrypt_test(
+ test_ecb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "CAST5"),
["cast5-ecb.txt"],
@@ -41,12 +41,12 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCAST5ModeCBC(object):
- test_CBC = generate_encrypt_test(
+ test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "CAST5"),
["cast5-cbc.txt"],
lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
)
@@ -58,12 +58,12 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCAST5ModeOFB(object):
- test_OFB = generate_encrypt_test(
+ test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "CAST5"),
["cast5-ofb.txt"],
lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)),
)
@@ -75,10 +75,10 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCAST5ModeCFB(object):
- test_CFB = generate_encrypt_test(
+ test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "CAST5"),
["cast5-cfb.txt"],
lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
)
diff --git a/tests/hazmat/primitives/test_chacha20.py b/tests/hazmat/primitives/test_chacha20.py
index 7c475c0..cb12d3c 100644
--- a/tests/hazmat/primitives/test_chacha20.py
+++ b/tests/hazmat/primitives/test_chacha20.py
@@ -30,8 +30,8 @@
_load_all_params(
os.path.join("ciphers", "ChaCha20"),
["rfc7539.txt"],
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_vectors(self, vector, backend):
key = binascii.unhexlify(vector["key"])
@@ -47,9 +47,7 @@
def test_buffer_protocol(self, backend):
key = bytearray(os.urandom(32))
nonce = bytearray(os.urandom(16))
- cipher = Cipher(
- algorithms.ChaCha20(key, nonce), None, backend
- )
+ cipher = Cipher(algorithms.ChaCha20(key, nonce), None, backend)
enc = cipher.encryptor()
ct = enc.update(bytearray(b"hello")) + enc.finalize()
dec = cipher.decryptor()
diff --git a/tests/hazmat/primitives/test_ciphers.py b/tests/hazmat/primitives/test_ciphers.py
index f29ba9a..a9219fe 100644
--- a/tests/hazmat/primitives/test_ciphers.py
+++ b/tests/hazmat/primitives/test_ciphers.py
@@ -14,20 +14,28 @@
from cryptography.hazmat.primitives import ciphers
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.primitives.ciphers.algorithms import (
- AES, ARC4, Blowfish, CAST5, Camellia, IDEA, SEED, TripleDES
+ AES,
+ ARC4,
+ Blowfish,
+ CAST5,
+ Camellia,
+ IDEA,
+ SEED,
+ TripleDES,
)
from ...utils import (
- load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
class TestAES(object):
- @pytest.mark.parametrize(("key", "keysize"), [
- (b"0" * 32, 128),
- (b"0" * 48, 192),
- (b"0" * 64, 256),
- ])
+ @pytest.mark.parametrize(
+ ("key", "keysize"),
+ [(b"0" * 32, 128), (b"0" * 48, 192), (b"0" * 64, 256)],
+ )
def test_key_size(self, key, keysize):
cipher = AES(binascii.unhexlify(key))
assert cipher.key_size == keysize
@@ -44,8 +52,7 @@
class TestAESXTS(object):
@pytest.mark.requires_backend_interface(interface=CipherBackend)
@pytest.mark.parametrize(
- "mode",
- (modes.CBC, modes.CTR, modes.CFB, modes.CFB8, modes.OFB)
+ "mode", (modes.CBC, modes.CTR, modes.CFB, modes.CFB8, modes.OFB)
)
def test_invalid_key_size_with_mode(self, mode, backend):
with pytest.raises(ValueError):
@@ -65,12 +72,18 @@
ciphers.Cipher(AES(b"0" * 16), modes.XTS(b"0" * 16), backend)
+class TestGCM(object):
+ @pytest.mark.parametrize("size", [7, 129])
+ def test_gcm_min_max(self, size):
+ with pytest.raises(ValueError):
+ modes.GCM(b"0" * size)
+
+
class TestCamellia(object):
- @pytest.mark.parametrize(("key", "keysize"), [
- (b"0" * 32, 128),
- (b"0" * 48, 192),
- (b"0" * 64, 256),
- ])
+ @pytest.mark.parametrize(
+ ("key", "keysize"),
+ [(b"0" * 32, 128), (b"0" * 48, 192), (b"0" * 64, 256)],
+ )
def test_key_size(self, key, keysize):
cipher = Camellia(binascii.unhexlify(key))
assert cipher.key_size == keysize
@@ -85,11 +98,7 @@
class TestTripleDES(object):
- @pytest.mark.parametrize("key", [
- b"0" * 16,
- b"0" * 32,
- b"0" * 48,
- ])
+ @pytest.mark.parametrize("key", [b"0" * 16, b"0" * 32, b"0" * 48])
def test_key_size(self, key):
cipher = TripleDES(binascii.unhexlify(key))
assert cipher.key_size == 192
@@ -104,9 +113,10 @@
class TestBlowfish(object):
- @pytest.mark.parametrize(("key", "keysize"), [
- (b"0" * (keysize // 4), keysize) for keysize in range(32, 449, 8)
- ])
+ @pytest.mark.parametrize(
+ ("key", "keysize"),
+ [(b"0" * (keysize // 4), keysize) for keysize in range(32, 449, 8)],
+ )
def test_key_size(self, key, keysize):
cipher = Blowfish(binascii.unhexlify(key))
assert cipher.key_size == keysize
@@ -121,9 +131,10 @@
class TestCAST5(object):
- @pytest.mark.parametrize(("key", "keysize"), [
- (b"0" * (keysize // 4), keysize) for keysize in range(40, 129, 8)
- ])
+ @pytest.mark.parametrize(
+ ("key", "keysize"),
+ [(b"0" * (keysize // 4), keysize) for keysize in range(40, 129, 8)],
+ )
def test_key_size(self, key, keysize):
cipher = CAST5(binascii.unhexlify(key))
assert cipher.key_size == keysize
@@ -138,15 +149,18 @@
class TestARC4(object):
- @pytest.mark.parametrize(("key", "keysize"), [
- (b"0" * 10, 40),
- (b"0" * 14, 56),
- (b"0" * 16, 64),
- (b"0" * 20, 80),
- (b"0" * 32, 128),
- (b"0" * 48, 192),
- (b"0" * 64, 256),
- ])
+ @pytest.mark.parametrize(
+ ("key", "keysize"),
+ [
+ (b"0" * 10, 40),
+ (b"0" * 14, 56),
+ (b"0" * 16, 64),
+ (b"0" * 20, 80),
+ (b"0" * 32, 128),
+ (b"0" * 48, 192),
+ (b"0" * 64, 256),
+ ],
+ )
def test_key_size(self, key, keysize):
cipher = ARC4(binascii.unhexlify(key))
assert cipher.key_size == keysize
@@ -207,8 +221,8 @@
"params",
load_vectors_from_file(
os.path.join("ciphers", "AES", "ECB", "ECBGFSbox128.rsp"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_update_into(self, params, backend):
key = binascii.unhexlify(params["key"])
@@ -272,8 +286,8 @@
"params",
load_vectors_from_file(
os.path.join("ciphers", "AES", "ECB", "ECBGFSbox128.rsp"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_update_into_multiple_calls(self, params, backend):
key = binascii.unhexlify(params["key"])
@@ -309,3 +323,29 @@
buf = bytearray(5)
with pytest.raises(ValueError):
encryptor.update_into(b"testing", buf)
+
+ def test_update_into_auto_chunking(self, backend, monkeypatch):
+ key = b"\x00" * 16
+ c = ciphers.Cipher(AES(key), modes.ECB(), backend)
+ encryptor = c.encryptor()
+ # Lower max chunk size so we can test chunking
+ monkeypatch.setattr(encryptor._ctx, "_MAX_CHUNK_SIZE", 40)
+ buf = bytearray(527)
+ pt = b"abcdefghijklmnopqrstuvwxyz012345" * 16 # 512 bytes
+ processed = encryptor.update_into(pt, buf)
+ assert processed == 512
+ decryptor = c.decryptor()
+ # Change max chunk size to verify alternate boundaries don't matter
+ monkeypatch.setattr(decryptor._ctx, "_MAX_CHUNK_SIZE", 73)
+ decbuf = bytearray(527)
+ decprocessed = decryptor.update_into(buf[:processed], decbuf)
+ assert decbuf[:decprocessed] == pt
+
+ def test_max_chunk_size_fits_in_int32(self, backend):
+ # max chunk must fit in signed int32 or else a call large enough to
+ # cause chunking will result in the very OverflowError we want to
+ # avoid with chunking.
+ key = b"\x00" * 16
+ c = ciphers.Cipher(AES(key), modes.ECB(), backend)
+ encryptor = c.encryptor()
+ backend._ffi.new("int *", encryptor._ctx._MAX_CHUNK_SIZE)
diff --git a/tests/hazmat/primitives/test_cmac.py b/tests/hazmat/primitives/test_cmac.py
index e319396..e4a35df 100644
--- a/tests/hazmat/primitives/test_cmac.py
+++ b/tests/hazmat/primitives/test_cmac.py
@@ -9,32 +9,42 @@
import pytest
from cryptography.exceptions import (
- AlreadyFinalized, InvalidSignature, _Reasons
+ AlreadyFinalized,
+ InvalidSignature,
+ _Reasons,
)
from cryptography.hazmat.backends.interfaces import CMACBackend
from cryptography.hazmat.primitives.ciphers.algorithms import (
- AES, ARC4, TripleDES
+ AES,
+ ARC4,
+ TripleDES,
)
from cryptography.hazmat.primitives.cmac import CMAC
from ...utils import (
- load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
vectors_aes128 = load_vectors_from_file(
- "CMAC/nist-800-38b-aes128.txt", load_nist_vectors)
+ "CMAC/nist-800-38b-aes128.txt", load_nist_vectors
+)
vectors_aes192 = load_vectors_from_file(
- "CMAC/nist-800-38b-aes192.txt", load_nist_vectors)
+ "CMAC/nist-800-38b-aes192.txt", load_nist_vectors
+)
vectors_aes256 = load_vectors_from_file(
- "CMAC/nist-800-38b-aes256.txt", load_nist_vectors)
+ "CMAC/nist-800-38b-aes256.txt", load_nist_vectors
+)
vectors_aes = vectors_aes128 + vectors_aes192 + vectors_aes256
vectors_3des = load_vectors_from_file(
- "CMAC/nist-800-38b-3des.txt", load_nist_vectors)
+ "CMAC/nist-800-38b-3des.txt", load_nist_vectors
+)
fake_key = b"\x00" * 16
@@ -43,8 +53,9 @@
class TestCMAC(object):
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- AES(fake_key)),
- skip_message="Does not support CMAC."
+ AES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
@pytest.mark.parametrize("params", vectors_aes)
def test_aes_generate(self, backend, params):
@@ -58,8 +69,9 @@
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- AES(fake_key)),
- skip_message="Does not support CMAC."
+ AES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
@pytest.mark.parametrize("params", vectors_aes)
def test_aes_verify(self, backend, params):
@@ -73,8 +85,9 @@
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- TripleDES(fake_key)),
- skip_message="Does not support CMAC."
+ TripleDES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
@pytest.mark.parametrize("params", vectors_3des)
def test_3des_generate(self, backend, params):
@@ -93,8 +106,9 @@
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- TripleDES(fake_key)),
- skip_message="Does not support CMAC."
+ TripleDES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
@pytest.mark.parametrize("params", vectors_3des)
def test_3des_verify(self, backend, params):
@@ -113,8 +127,9 @@
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- AES(fake_key)),
- skip_message="Does not support CMAC."
+ AES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
def test_invalid_verify(self, backend):
key = b"2b7e151628aed2a6abf7158809cf4f3c"
@@ -125,9 +140,8 @@
cmac.verify(b"foobar")
@pytest.mark.supported(
- only_if=lambda backend: backend.cipher_supported(
- ARC4(fake_key), None),
- skip_message="Does not support CMAC."
+ only_if=lambda backend: backend.cipher_supported(ARC4(fake_key), None),
+ skip_message="Does not support CMAC.",
)
def test_invalid_algorithm(self, backend):
key = b"0102030405"
@@ -136,8 +150,9 @@
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- AES(fake_key)),
- skip_message="Does not support CMAC."
+ AES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
def test_raises_after_finalize(self, backend):
key = b"2b7e151628aed2a6abf7158809cf4f3c"
@@ -158,23 +173,25 @@
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- AES(fake_key)),
- skip_message="Does not support CMAC."
+ AES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
def test_verify_reject_unicode(self, backend):
key = b"2b7e151628aed2a6abf7158809cf4f3c"
cmac = CMAC(AES(key), backend)
with pytest.raises(TypeError):
- cmac.update(u'')
+ cmac.update(u"")
with pytest.raises(TypeError):
- cmac.verify(u'')
+ cmac.verify(u"")
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- AES(fake_key)),
- skip_message="Does not support CMAC."
+ AES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
def test_copy_with_backend(self, backend):
key = b"2b7e151628aed2a6abf7158809cf4f3c"
@@ -185,8 +202,9 @@
@pytest.mark.supported(
only_if=lambda backend: backend.cmac_algorithm_supported(
- AES(fake_key)),
- skip_message="Does not support CMAC."
+ AES(fake_key)
+ ),
+ skip_message="Does not support CMAC.",
)
def test_buffer_protocol(self, backend):
key = bytearray(b"2b7e151628aed2a6abf7158809cf4f3c")
diff --git a/tests/hazmat/primitives/test_concatkdf.py b/tests/hazmat/primitives/test_concatkdf.py
index 6731509..271e011 100644
--- a/tests/hazmat/primitives/test_concatkdf.py
+++ b/tests/hazmat/primitives/test_concatkdf.py
@@ -8,9 +8,7 @@
import pytest
-from cryptography.exceptions import (
- AlreadyFinalized, InvalidKey, _Reasons
-)
+from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons
from cryptography.hazmat.backends.interfaces import HMACBackend
from cryptography.hazmat.backends.interfaces import HashBackend
from cryptography.hazmat.primitives import hashes
@@ -102,38 +100,26 @@
def test_unicode_typeerror(self, backend):
with pytest.raises(TypeError):
ConcatKDFHash(
- hashes.SHA256(),
- 16,
- otherinfo=u"foo",
- backend=backend
+ hashes.SHA256(), 16, otherinfo=u"foo", backend=backend
)
with pytest.raises(TypeError):
ckdf = ConcatKDFHash(
- hashes.SHA256(),
- 16,
- otherinfo=None,
- backend=backend
+ hashes.SHA256(), 16, otherinfo=None, backend=backend
)
ckdf.derive(u"foo")
with pytest.raises(TypeError):
ckdf = ConcatKDFHash(
- hashes.SHA256(),
- 16,
- otherinfo=None,
- backend=backend
+ hashes.SHA256(), 16, otherinfo=None, backend=backend
)
ckdf.verify(u"foo", b"bar")
with pytest.raises(TypeError):
ckdf = ConcatKDFHash(
- hashes.SHA256(),
- 16,
- otherinfo=None,
- backend=backend
+ hashes.SHA256(), 16, otherinfo=None, backend=backend
)
ckdf.verify(b"foo", u"bar")
@@ -162,8 +148,10 @@
b"8f0af7fce1d045edbc5790931e8d5ca79c73"
)
- okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7"
- b"605323ce2f39bf27eaaac8b34cf89f2f")
+ okm = binascii.unhexlify(
+ b"64ce901db10d558661f10b6836a122a7"
+ b"605323ce2f39bf27eaaac8b34cf89f2f"
+ )
oinfo = binascii.unhexlify(
b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c"
@@ -181,8 +169,10 @@
b"8f0af7fce1d045edbc5790931e8d5ca79c73"
)
- okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7"
- b"605323ce2f39bf27eaaac8b34cf89f2f")
+ okm = binascii.unhexlify(
+ b"64ce901db10d558661f10b6836a122a7"
+ b"605323ce2f39bf27eaaac8b34cf89f2f"
+ )
oinfo = binascii.unhexlify(
b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c"
@@ -200,8 +190,10 @@
b"8f0af7fce1d045edbc5790931e8d5ca79c73"
)
- okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7"
- b"605323ce2f39bf27eaaac8b34cf89f2f")
+ okm = binascii.unhexlify(
+ b"64ce901db10d558661f10b6836a122a7"
+ b"605323ce2f39bf27eaaac8b34cf89f2f"
+ )
oinfo = binascii.unhexlify(
b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c"
@@ -221,8 +213,10 @@
b"8f0af7fce1d045edbc5790931e8d5ca79c73"
)
- okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7"
- b"605323ce2f39bf27eaaac8b34cf89f2f")
+ okm = binascii.unhexlify(
+ b"64ce901db10d558661f10b6836a122a7"
+ b"605323ce2f39bf27eaaac8b34cf89f2f"
+ )
oinfo = binascii.unhexlify(
b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c"
@@ -254,45 +248,38 @@
with pytest.raises(TypeError):
ConcatKDFHMAC(
hashes.SHA256(),
- 16, salt=u"foo",
+ 16,
+ salt=u"foo",
otherinfo=None,
- backend=backend
+ backend=backend,
)
with pytest.raises(TypeError):
ConcatKDFHMAC(
hashes.SHA256(),
- 16, salt=None,
+ 16,
+ salt=None,
otherinfo=u"foo",
- backend=backend
+ backend=backend,
)
with pytest.raises(TypeError):
ckdf = ConcatKDFHMAC(
- hashes.SHA256(),
- 16, salt=None,
- otherinfo=None,
- backend=backend
+ hashes.SHA256(), 16, salt=None, otherinfo=None, backend=backend
)
ckdf.derive(u"foo")
with pytest.raises(TypeError):
ckdf = ConcatKDFHMAC(
- hashes.SHA256(),
- 16, salt=None,
- otherinfo=None,
- backend=backend
+ hashes.SHA256(), 16, salt=None, otherinfo=None, backend=backend
)
ckdf.verify(u"foo", b"bar")
with pytest.raises(TypeError):
ckdf = ConcatKDFHMAC(
- hashes.SHA256(),
- 16, salt=None,
- otherinfo=None,
- backend=backend
+ hashes.SHA256(), 16, salt=None, otherinfo=None, backend=backend
)
ckdf.verify(b"foo", u"bar")
diff --git a/tests/hazmat/primitives/test_dh.py b/tests/hazmat/primitives/test_dh.py
index c667cd1..bc5ed8f 100644
--- a/tests/hazmat/primitives/test_dh.py
+++ b/tests/hazmat/primitives/test_dh.py
@@ -11,119 +11,114 @@
import pytest
from cryptography.hazmat.backends.interfaces import (
- DERSerializationBackend, DHBackend, PEMSerializationBackend)
+ DERSerializationBackend,
+ DHBackend,
+ PEMSerializationBackend,
+)
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import dh
from cryptography.utils import int_from_bytes
+from .fixtures_dh import FFDH3072_P
from ...doubles import DummyKeySerializationEncryption
from ...utils import load_nist_vectors, load_vectors_from_file
+# RFC 3526
+P_1536 = int(
+ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF",
+ 16,
+)
+
def _skip_dhx_unsupported(backend, is_dhx):
if not is_dhx:
return
if not backend.dh_x942_serialization_supported():
- pytest.skip(
- "DH x9.42 serialization is not supported"
- )
+ pytest.skip("DH x9.42 serialization is not supported")
def test_dh_parameternumbers():
- params = dh.DHParameterNumbers(
- 65537, 2
- )
+ params = dh.DHParameterNumbers(P_1536, 2)
- assert params.p == 65537
+ assert params.p == P_1536
assert params.g == 2
with pytest.raises(TypeError):
- dh.DHParameterNumbers(
- None, 2
- )
+ dh.DHParameterNumbers(None, 2)
with pytest.raises(TypeError):
- dh.DHParameterNumbers(
- 65537, None
- )
+ dh.DHParameterNumbers(P_1536, None)
with pytest.raises(TypeError):
- dh.DHParameterNumbers(
- None, None
- )
+ dh.DHParameterNumbers(None, None)
with pytest.raises(ValueError):
- dh.DHParameterNumbers(
- 65537, 1
- )
+ dh.DHParameterNumbers(P_1536, 1)
- params = dh.DHParameterNumbers(
- 65537, 7, 1245
- )
+ # p too small
+ with pytest.raises(ValueError):
+ dh.DHParameterNumbers(65537, 2)
- assert params.p == 65537
+ params = dh.DHParameterNumbers(P_1536, 7, 1245)
+
+ assert params.p == P_1536
assert params.g == 7
assert params.q == 1245
with pytest.raises(TypeError):
- dh.DHParameterNumbers(
- 65537, 2, "hello"
- )
+ dh.DHParameterNumbers(P_1536, 2, "hello")
def test_dh_numbers():
- params = dh.DHParameterNumbers(
- 65537, 2
- )
+ params = dh.DHParameterNumbers(P_1536, 2)
- public = dh.DHPublicNumbers(
- 1, params
- )
+ public = dh.DHPublicNumbers(1, params)
assert public.parameter_numbers is params
assert public.y == 1
with pytest.raises(TypeError):
- dh.DHPublicNumbers(
- 1, None
- )
+ dh.DHPublicNumbers(1, None)
with pytest.raises(TypeError):
- dh.DHPublicNumbers(
- None, params
- )
+ dh.DHPublicNumbers(None, params)
- private = dh.DHPrivateNumbers(
- 1, public
- )
+ private = dh.DHPrivateNumbers(1, public)
assert private.public_numbers is public
assert private.x == 1
with pytest.raises(TypeError):
- dh.DHPrivateNumbers(
- 1, None
- )
+ dh.DHPrivateNumbers(1, None)
with pytest.raises(TypeError):
- dh.DHPrivateNumbers(
- None, public
- )
+ dh.DHPrivateNumbers(None, public)
def test_dh_parameter_numbers_equality():
- assert dh.DHParameterNumbers(65537, 2) == dh.DHParameterNumbers(65537, 2)
- assert dh.DHParameterNumbers(65537, 7, 12345) == dh.DHParameterNumbers(
- 65537, 7, 12345)
- assert dh.DHParameterNumbers(6, 2) != dh.DHParameterNumbers(65537, 2)
- assert dh.DHParameterNumbers(65537, 2, 123) != dh.DHParameterNumbers(
- 65537, 2, 456)
- assert dh.DHParameterNumbers(65537, 5) != dh.DHParameterNumbers(65537, 2)
- assert dh.DHParameterNumbers(65537, 2) != object()
+ assert dh.DHParameterNumbers(P_1536, 2) == dh.DHParameterNumbers(P_1536, 2)
+ assert dh.DHParameterNumbers(P_1536, 7, 12345) == dh.DHParameterNumbers(
+ P_1536, 7, 12345
+ )
+ assert dh.DHParameterNumbers(P_1536 + 2, 2) != dh.DHParameterNumbers(
+ P_1536, 2
+ )
+ assert dh.DHParameterNumbers(P_1536, 2, 123) != dh.DHParameterNumbers(
+ P_1536, 2, 456
+ )
+ assert dh.DHParameterNumbers(P_1536, 5) != dh.DHParameterNumbers(P_1536, 2)
+ assert dh.DHParameterNumbers(P_1536, 2) != object()
def test_dh_private_numbers_equality():
- params = dh.DHParameterNumbers(65537, 2)
+ params = dh.DHParameterNumbers(P_1536, 2)
public = dh.DHPublicNumbers(1, params)
private = dh.DHPrivateNumbers(2, public)
@@ -131,18 +126,18 @@
assert private != dh.DHPrivateNumbers(0, public)
assert private != dh.DHPrivateNumbers(2, dh.DHPublicNumbers(0, params))
assert private != dh.DHPrivateNumbers(
- 2, dh.DHPublicNumbers(1, dh.DHParameterNumbers(65537, 5))
+ 2, dh.DHPublicNumbers(1, dh.DHParameterNumbers(P_1536, 5))
)
assert private != object()
def test_dh_public_numbers_equality():
- params = dh.DHParameterNumbers(65537, 2)
+ params = dh.DHParameterNumbers(P_1536, 2)
public = dh.DHPublicNumbers(1, params)
assert public == dh.DHPublicNumbers(1, params)
assert public != dh.DHPublicNumbers(0, params)
- assert public != dh.DHPublicNumbers(1, dh.DHParameterNumbers(65537, 5))
+ assert public != dh.DHPublicNumbers(1, dh.DHParameterNumbers(P_1536, 5))
assert public != object()
@@ -156,19 +151,33 @@
with pytest.raises(ValueError):
dh.generate_parameters(7, 512, backend)
+ @pytest.mark.skip_fips(reason="non-FIPS parameters")
def test_dh_parameters_supported(self, backend):
- assert backend.dh_parameters_supported(23, 5)
- assert not backend.dh_parameters_supported(23, 18)
+ valid_p = int(
+ b"907c7211ae61aaaba1825ff53b6cb71ac6df9f1a424c033f4a0a41ac42fad3a9"
+ b"bcfc7f938a269710ed69e330523e4039029b7900977c740990d46efed79b9bbe"
+ b"73505ae878808944ce4d9c6c52daecc0a87dc889c53499be93db8551ee685f30"
+ b"349bf1b443d4ebaee0d5e8b441a40d4e8178f8f612f657a5eb91e0a8e"
+ b"107755f",
+ 16,
+ )
+ assert backend.dh_parameters_supported(valid_p, 5)
+ assert not backend.dh_parameters_supported(23, 22)
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join("asymmetric", "DH", "rfc3526.txt"),
- load_nist_vectors
- )
+ os.path.join("asymmetric", "DH", "rfc3526.txt"), load_nist_vectors
+ ),
)
def test_dh_parameters_allows_rfc3526_groups(self, backend, vector):
- p = int_from_bytes(binascii.unhexlify(vector["p"]), 'big')
+ p = int_from_bytes(binascii.unhexlify(vector["p"]), "big")
+ if (
+ backend._fips_enabled
+ and p.bit_length() < backend._fips_dh_min_modulus
+ ):
+ pytest.skip("modulus too small for FIPS mode")
+
params = dh.DHParameterNumbers(p, int(vector["g"]))
param = params.parameters(backend)
key = param.generate_private_key()
@@ -178,22 +187,26 @@
roundtripped_key = key.private_numbers().private_key(backend)
assert key.private_numbers() == roundtripped_key.private_numbers()
+ @pytest.mark.skip_fips(reason="non-FIPS parameters")
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join("asymmetric", "DH", "RFC5114.txt"),
- load_nist_vectors))
+ os.path.join("asymmetric", "DH", "RFC5114.txt"), load_nist_vectors
+ ),
+ )
def test_dh_parameters_supported_with_q(self, backend, vector):
- assert backend.dh_parameters_supported(int(vector["p"], 16),
- int(vector["g"], 16),
- int(vector["q"], 16))
+ assert backend.dh_parameters_supported(
+ int(vector["p"], 16), int(vector["g"], 16), int(vector["q"], 16)
+ )
+ @pytest.mark.skip_fips(reason="modulus too small for FIPS")
@pytest.mark.parametrize("with_q", [False, True])
def test_convert_to_numbers(self, backend, with_q):
if with_q:
vector = load_vectors_from_file(
os.path.join("asymmetric", "DH", "RFC5114.txt"),
- load_nist_vectors)[0]
+ load_nist_vectors,
+ )[0]
p = int(vector["p"], 16)
g = int(vector["g"], 16)
q = int(vector["q"], 16)
@@ -214,32 +227,35 @@
deserialized_public = public.public_key(backend)
deserialized_private = private.private_key(backend)
- assert isinstance(deserialized_params,
- dh.DHParametersWithSerialization)
- assert isinstance(deserialized_public,
- dh.DHPublicKeyWithSerialization)
- assert isinstance(deserialized_private,
- dh.DHPrivateKeyWithSerialization)
+ assert isinstance(
+ deserialized_params, dh.DHParametersWithSerialization
+ )
+ assert isinstance(deserialized_public, dh.DHPublicKeyWithSerialization)
+ assert isinstance(
+ deserialized_private, dh.DHPrivateKeyWithSerialization
+ )
+ @pytest.mark.skip_fips(reason="FIPS requires specific parameters")
def test_numbers_unsupported_parameters(self, backend):
- # p is set to 21 because when calling private_key we want it to
- # fail the DH_check call OpenSSL does. Originally this was 23, but
- # we are allowing p % 24 to == 23 with this PR (see #3768 for more)
- # By setting it to 21 it fails later in DH_check in a primality check
- # which triggers the code path we want to test
- params = dh.DHParameterNumbers(21, 2)
+ # p is set to P_1536 + 1 because when calling private_key we want it to
+ # fail the DH_check call OpenSSL does, but we specifically want it to
+ # fail such that we don't get a DH_NOT_SUITABLE_GENERATOR. We can cause
+ # this by making sure p is not prime.
+ params = dh.DHParameterNumbers(P_1536 + 1, 2)
public = dh.DHPublicNumbers(1, params)
private = dh.DHPrivateNumbers(2, public)
with pytest.raises(ValueError):
private.private_key(backend)
+ @pytest.mark.skip_fips(reason="FIPS requires key size >= 2048")
@pytest.mark.parametrize("with_q", [False, True])
def test_generate_dh(self, backend, with_q):
if with_q:
vector = load_vectors_from_file(
os.path.join("asymmetric", "DH", "RFC5114.txt"),
- load_nist_vectors)[0]
+ load_nist_vectors,
+ )[0]
p = int(vector["p"], 16)
g = int(vector["g"], 16)
q = int(vector["q"], 16)
@@ -274,7 +290,7 @@
assert isinstance(key.parameters(), dh.DHParameters)
def test_exchange(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
assert isinstance(parameters, dh.DHParameters)
key1 = parameters.generate_private_key()
@@ -282,65 +298,82 @@
symkey1 = key1.exchange(key2.public_key())
assert symkey1
- assert len(symkey1) == 512 // 8
+ assert len(symkey1) == 3072 // 8
symkey2 = key2.exchange(key1.public_key())
assert symkey1 == symkey2
def test_exchange_algorithm(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
-
+ parameters = FFDH3072_P.parameters(backend)
key1 = parameters.generate_private_key()
key2 = parameters.generate_private_key()
shared_key_bytes = key2.exchange(key1.public_key())
- symkey = int_from_bytes(shared_key_bytes, 'big')
+ symkey = int_from_bytes(shared_key_bytes, "big")
- symkey_manual = pow(key1.public_key().public_numbers().y,
- key2.private_numbers().x,
- parameters.parameter_numbers().p)
+ symkey_manual = pow(
+ key1.public_key().public_numbers().y,
+ key2.private_numbers().x,
+ parameters.parameter_numbers().p,
+ )
assert symkey == symkey_manual
+ @pytest.mark.skip_fips(reason="key_size too small for FIPS")
def test_symmetric_key_padding(self, backend):
"""
This test has specific parameters that produce a symmetric key
In length 63 bytes instead 64. We make sure here that we add
padding to the key.
"""
- p = int("11859949538425015739337467917303613431031019140213666"
- "129025407300654026585086345323066284800963463204246390"
- "256567934582260424238844463330887962689642467123")
+ p = int(
+ "11859949538425015739337467917303613431031019140213666"
+ "129025407300654026585086345323066284800963463204246390"
+ "256567934582260424238844463330887962689642467123"
+ )
g = 2
- y = int("32155788395534640648739966373159697798396966919821525"
- "72238852825117261342483718574508213761865276905503199"
- "969908098203345481366464874759377454476688391248")
- x = int("409364065449673443397833358558926598469347813468816037"
- "268451847116982490733450463194921405069999008617231539"
- "7147035896687401350877308899732826446337707128")
+ y = int(
+ "32155788395534640648739966373159697798396966919821525"
+ "72238852825117261342483718574508213761865276905503199"
+ "969908098203345481366464874759377454476688391248"
+ )
+ x = int(
+ "409364065449673443397833358558926598469347813468816037"
+ "268451847116982490733450463194921405069999008617231539"
+ "7147035896687401350877308899732826446337707128"
+ )
parameters = dh.DHParameterNumbers(p, g)
public = dh.DHPublicNumbers(y, parameters)
private = dh.DHPrivateNumbers(x, public)
key = private.private_key(backend)
symkey = key.exchange(public.public_key(backend))
assert len(symkey) == 512 // 8
- assert symkey[:1] == b'\x00'
+ assert symkey[:1] == b"\x00"
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "DH", "bad_exchange.txt"),
- load_nist_vectors))
+ load_nist_vectors,
+ ),
+ )
def test_bad_exchange(self, backend, vector):
- parameters1 = dh.DHParameterNumbers(int(vector["p1"]),
- int(vector["g"]))
+ if (
+ backend._fips_enabled
+ and int(vector["p1"]) < backend._fips_dh_min_modulus
+ ):
+ pytest.skip("modulus too small for FIPS mode")
+ parameters1 = dh.DHParameterNumbers(
+ int(vector["p1"]), int(vector["g"])
+ )
public1 = dh.DHPublicNumbers(int(vector["y1"]), parameters1)
private1 = dh.DHPrivateNumbers(int(vector["x1"]), public1)
key1 = private1.private_key(backend)
pub_key1 = key1.public_key()
- parameters2 = dh.DHParameterNumbers(int(vector["p2"]),
- int(vector["g"]))
+ parameters2 = dh.DHParameterNumbers(
+ int(vector["p2"]), int(vector["g"])
+ )
public2 = dh.DHPublicNumbers(int(vector["y2"]), parameters2)
private2 = dh.DHPrivateNumbers(int(vector["x2"]), public2)
key2 = private2.private_key(backend)
@@ -357,30 +390,51 @@
assert symkey1 != symkey2
+ @pytest.mark.skip_fips(reason="key_size too small for FIPS")
+ def test_load_256bit_key_from_pkcs8(self, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", "DH", "dh_key_256.pem"),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ key = serialization.load_pem_private_key(data, None, backend)
+ assert key.key_size == 256
+
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join("asymmetric", "DH", "vec.txt"),
- load_nist_vectors))
+ os.path.join("asymmetric", "DH", "vec.txt"), load_nist_vectors
+ ),
+ )
def test_dh_vectors(self, backend, vector):
- parameters = dh.DHParameterNumbers(int(vector["p"]),
- int(vector["g"]))
+ if (
+ backend._fips_enabled
+ and int(vector["p"]) < backend._fips_dh_min_modulus
+ ):
+ pytest.skip("modulus too small for FIPS mode")
+
+ if int(vector["p"]).bit_length() < 512:
+ pytest.skip("DH keys less than 512 bits are unsupported")
+
+ parameters = dh.DHParameterNumbers(int(vector["p"]), int(vector["g"]))
public = dh.DHPublicNumbers(int(vector["y"]), parameters)
private = dh.DHPrivateNumbers(int(vector["x"]), public)
key = private.private_key(backend)
symkey = key.exchange(public.public_key(backend))
- assert int_from_bytes(symkey, 'big') == int(vector["k"], 16)
+ assert int_from_bytes(symkey, "big") == int(vector["k"], 16)
+ @pytest.mark.skip_fips(reason="non-FIPS parameters")
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join("asymmetric", "DH", "RFC5114.txt"),
- load_nist_vectors))
+ os.path.join("asymmetric", "DH", "RFC5114.txt"), load_nist_vectors
+ ),
+ )
def test_dh_vectors_with_q(self, backend, vector):
- parameters = dh.DHParameterNumbers(int(vector["p"], 16),
- int(vector["g"], 16),
- int(vector["q"], 16))
+ parameters = dh.DHParameterNumbers(
+ int(vector["p"], 16), int(vector["g"], 16), int(vector["q"], 16)
+ )
public1 = dh.DHPublicNumbers(int(vector["ystatcavs"], 16), parameters)
private1 = dh.DHPrivateNumbers(int(vector["xstatcavs"], 16), public1)
public2 = dh.DHPublicNumbers(int(vector["ystatiut"], 16), parameters)
@@ -390,35 +444,28 @@
symkey1 = key1.exchange(public2.public_key(backend))
symkey2 = key2.exchange(public1.public_key(backend))
- assert int_from_bytes(symkey1, 'big') == int(vector["z"], 16)
- assert int_from_bytes(symkey2, 'big') == int(vector["z"], 16)
+ assert int_from_bytes(symkey1, "big") == int(vector["z"], 16)
+ assert int_from_bytes(symkey2, "big") == int(vector["z"], 16)
@pytest.mark.requires_backend_interface(interface=DHBackend)
@pytest.mark.requires_backend_interface(interface=PEMSerializationBackend)
@pytest.mark.requires_backend_interface(interface=DERSerializationBackend)
class TestDHPrivateKeySerialization(object):
-
@pytest.mark.parametrize(
("encoding", "loader_func"),
[
- [
- serialization.Encoding.PEM,
- serialization.load_pem_private_key
- ],
- [
- serialization.Encoding.DER,
- serialization.load_der_private_key
- ],
- ]
+ [serialization.Encoding.PEM, serialization.load_pem_private_key],
+ [serialization.Encoding.DER, serialization.load_der_private_key],
+ ],
)
- def test_private_bytes_unencrypted(self, backend, encoding,
- loader_func):
- parameters = dh.generate_parameters(2, 512, backend)
+ def test_private_bytes_unencrypted(self, backend, encoding, loader_func):
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key()
serialized = key.private_bytes(
- encoding, serialization.PrivateFormat.PKCS8,
- serialization.NoEncryption()
+ encoding,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
)
loaded_key = loader_func(serialized, None, backend)
loaded_priv_num = loaded_key.private_numbers()
@@ -432,14 +479,15 @@
(serialization.Encoding.DER, serialization.PrivateFormat.Raw),
(serialization.Encoding.Raw, serialization.PrivateFormat.Raw),
(serialization.Encoding.X962, serialization.PrivateFormat.PKCS8),
- ]
+ ],
)
def test_private_bytes_rejects_invalid(self, encoding, fmt, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key()
with pytest.raises(ValueError):
key.private_bytes(encoding, fmt, serialization.NoEncryption())
+ @pytest.mark.skip_fips(reason="non-FIPS parameters")
@pytest.mark.parametrize(
("key_path", "loader_func", "encoding", "is_dhx"),
[
@@ -448,38 +496,43 @@
serialization.load_pem_private_key,
serialization.Encoding.PEM,
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhkey.der"),
serialization.load_der_private_key,
serialization.Encoding.DER,
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.pem"),
serialization.load_pem_private_key,
serialization.Encoding.PEM,
True,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.der"),
serialization.load_der_private_key,
serialization.Encoding.DER,
True,
- )
- ]
+ ),
+ ],
)
- def test_private_bytes_match(self, key_path, loader_func,
- encoding, is_dhx, backend):
+ def test_private_bytes_match(
+ self, key_path, loader_func, encoding, is_dhx, backend
+ ):
_skip_dhx_unsupported(backend, is_dhx)
key_bytes = load_vectors_from_file(
- key_path,
- lambda pemfile: pemfile.read(), mode="rb"
+ key_path, lambda pemfile: pemfile.read(), mode="rb"
)
key = loader_func(key_bytes, None, backend)
serialized = key.private_bytes(
- encoding, serialization.PrivateFormat.PKCS8,
- serialization.NoEncryption()
+ encoding,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
)
assert serialized == key_bytes
+ @pytest.mark.skip_fips(reason="non-FIPS parameters")
@pytest.mark.parametrize(
("key_path", "loader_func", "vec_path", "is_dhx"),
[
@@ -488,30 +541,33 @@
serialization.load_pem_private_key,
os.path.join("asymmetric", "DH", "dhkey.txt"),
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhkey.der"),
serialization.load_der_private_key,
os.path.join("asymmetric", "DH", "dhkey.txt"),
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.pem"),
serialization.load_pem_private_key,
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"),
True,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.der"),
serialization.load_der_private_key,
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"),
True,
- )
- ]
+ ),
+ ],
)
- def test_private_bytes_values(self, key_path, loader_func,
- vec_path, is_dhx, backend):
+ def test_private_bytes_values(
+ self, key_path, loader_func, vec_path, is_dhx, backend
+ ):
_skip_dhx_unsupported(backend, is_dhx)
key_bytes = load_vectors_from_file(
- key_path,
- lambda pemfile: pemfile.read(), mode="rb"
+ key_path, lambda pemfile: pemfile.read(), mode="rb"
)
vec = load_vectors_from_file(vec_path, load_nist_vectors)[0]
key = loader_func(key_bytes, None, backend)
@@ -519,63 +575,66 @@
assert private_numbers.x == int(vec["x"], 16)
assert private_numbers.public_numbers.y == int(vec["y"], 16)
assert private_numbers.public_numbers.parameter_numbers.g == int(
- vec["g"], 16)
+ vec["g"], 16
+ )
assert private_numbers.public_numbers.parameter_numbers.p == int(
- vec["p"], 16)
+ vec["p"], 16
+ )
if "q" in vec:
assert private_numbers.public_numbers.parameter_numbers.q == int(
- vec["q"], 16)
+ vec["q"], 16
+ )
else:
assert private_numbers.public_numbers.parameter_numbers.q is None
def test_private_bytes_traditional_openssl_invalid(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key()
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_encoding(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key()
with pytest.raises(TypeError):
key.private_bytes(
"notencoding",
serialization.PrivateFormat.PKCS8,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_format(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key()
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
"invalidformat",
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_encryption_algorithm(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key()
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
- "notanencalg"
+ "notanencalg",
)
def test_private_bytes_unsupported_encryption_type(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key()
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
- DummyKeySerializationEncryption()
+ DummyKeySerializationEncryption(),
)
@@ -583,23 +642,15 @@
@pytest.mark.requires_backend_interface(interface=PEMSerializationBackend)
@pytest.mark.requires_backend_interface(interface=DERSerializationBackend)
class TestDHPublicKeySerialization(object):
-
@pytest.mark.parametrize(
("encoding", "loader_func"),
[
- [
- serialization.Encoding.PEM,
- serialization.load_pem_public_key
- ],
- [
- serialization.Encoding.DER,
- serialization.load_der_public_key
- ],
- ]
+ [serialization.Encoding.PEM, serialization.load_pem_public_key],
+ [serialization.Encoding.DER, serialization.load_der_public_key],
+ ],
)
- def test_public_bytes(self, backend, encoding,
- loader_func):
- parameters = dh.generate_parameters(2, 512, backend)
+ def test_public_bytes(self, backend, encoding, loader_func):
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key().public_key()
serialized = key.public_bytes(
encoding, serialization.PublicFormat.SubjectPublicKeyInfo
@@ -617,30 +668,33 @@
serialization.load_pem_public_key,
serialization.Encoding.PEM,
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhpub.der"),
serialization.load_der_public_key,
serialization.Encoding.DER,
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.pem"),
serialization.load_pem_public_key,
serialization.Encoding.PEM,
True,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.der"),
serialization.load_der_public_key,
serialization.Encoding.DER,
True,
- )
- ]
+ ),
+ ],
)
- def test_public_bytes_match(self, key_path, loader_func,
- encoding, is_dhx, backend):
+ def test_public_bytes_match(
+ self, key_path, loader_func, encoding, is_dhx, backend
+ ):
_skip_dhx_unsupported(backend, is_dhx)
key_bytes = load_vectors_from_file(
- key_path,
- lambda pemfile: pemfile.read(), mode="rb"
+ key_path, lambda pemfile: pemfile.read(), mode="rb"
)
pub_key = loader_func(key_bytes, backend)
serialized = pub_key.public_bytes(
@@ -657,30 +711,33 @@
serialization.load_pem_public_key,
os.path.join("asymmetric", "DH", "dhkey.txt"),
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhpub.der"),
serialization.load_der_public_key,
os.path.join("asymmetric", "DH", "dhkey.txt"),
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.pem"),
serialization.load_pem_public_key,
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"),
True,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.der"),
serialization.load_der_public_key,
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"),
True,
- )
- ]
+ ),
+ ],
)
- def test_public_bytes_values(self, key_path, loader_func,
- vec_path, is_dhx, backend):
+ def test_public_bytes_values(
+ self, key_path, loader_func, vec_path, is_dhx, backend
+ ):
_skip_dhx_unsupported(backend, is_dhx)
key_bytes = load_vectors_from_file(
- key_path,
- lambda pemfile: pemfile.read(), mode="rb"
+ key_path, lambda pemfile: pemfile.read(), mode="rb"
)
vec = load_vectors_from_file(vec_path, load_nist_vectors)[0]
pub_key = loader_func(key_bytes, backend)
@@ -694,16 +751,15 @@
assert public_numbers.parameter_numbers.q is None
def test_public_bytes_invalid_encoding(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key().public_key()
with pytest.raises(TypeError):
key.public_bytes(
- "notencoding",
- serialization.PublicFormat.SubjectPublicKeyInfo
+ "notencoding", serialization.PublicFormat.SubjectPublicKeyInfo
)
def test_public_bytes_pkcs1_unsupported(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key().public_key()
with pytest.raises(ValueError):
key.public_bytes(
@@ -715,23 +771,15 @@
@pytest.mark.requires_backend_interface(interface=PEMSerializationBackend)
@pytest.mark.requires_backend_interface(interface=DERSerializationBackend)
class TestDHParameterSerialization(object):
-
@pytest.mark.parametrize(
("encoding", "loader_func"),
[
- [
- serialization.Encoding.PEM,
- serialization.load_pem_parameters
- ],
- [
- serialization.Encoding.DER,
- serialization.load_der_parameters
- ],
- ]
+ [serialization.Encoding.PEM, serialization.load_pem_parameters],
+ [serialization.Encoding.DER, serialization.load_der_parameters],
+ ],
)
- def test_parameter_bytes(self, backend, encoding,
- loader_func):
- parameters = dh.generate_parameters(2, 512, backend)
+ def test_parameter_bytes(self, backend, encoding, loader_func):
+ parameters = FFDH3072_P.parameters(backend)
serialized = parameters.parameter_bytes(
encoding, serialization.ParameterFormat.PKCS3
)
@@ -747,30 +795,33 @@
serialization.load_pem_parameters,
serialization.Encoding.PEM,
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhp.der"),
serialization.load_der_parameters,
serialization.Encoding.DER,
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhp_rfc5114_2.pem"),
serialization.load_pem_parameters,
serialization.Encoding.PEM,
True,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhp_rfc5114_2.der"),
serialization.load_der_parameters,
serialization.Encoding.DER,
True,
- )
- ]
+ ),
+ ],
)
- def test_parameter_bytes_match(self, param_path, loader_func,
- encoding, backend, is_dhx):
+ def test_parameter_bytes_match(
+ self, param_path, loader_func, encoding, backend, is_dhx
+ ):
_skip_dhx_unsupported(backend, is_dhx)
param_bytes = load_vectors_from_file(
- param_path,
- lambda pemfile: pemfile.read(), mode="rb"
+ param_path, lambda pemfile: pemfile.read(), mode="rb"
)
parameters = loader_func(param_bytes, backend)
serialized = parameters.parameter_bytes(
@@ -787,30 +838,33 @@
serialization.load_pem_parameters,
os.path.join("asymmetric", "DH", "dhkey.txt"),
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhp.der"),
serialization.load_der_parameters,
os.path.join("asymmetric", "DH", "dhkey.txt"),
False,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhp_rfc5114_2.pem"),
serialization.load_pem_parameters,
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"),
True,
- ), (
+ ),
+ (
os.path.join("asymmetric", "DH", "dhp_rfc5114_2.der"),
serialization.load_der_parameters,
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"),
True,
- )
- ]
+ ),
+ ],
)
- def test_public_bytes_values(self, param_path, loader_func,
- vec_path, backend, is_dhx):
+ def test_public_bytes_values(
+ self, param_path, loader_func, vec_path, backend, is_dhx
+ ):
_skip_dhx_unsupported(backend, is_dhx)
key_bytes = load_vectors_from_file(
- param_path,
- lambda pemfile: pemfile.read(), mode="rb"
+ param_path, lambda pemfile: pemfile.read(), mode="rb"
)
vec = load_vectors_from_file(vec_path, load_nist_vectors)[0]
parameters = loader_func(key_bytes, backend)
@@ -827,49 +881,48 @@
[
(
serialization.Encoding.Raw,
- serialization.PublicFormat.SubjectPublicKeyInfo
+ serialization.PublicFormat.SubjectPublicKeyInfo,
),
(serialization.Encoding.Raw, serialization.PublicFormat.PKCS1),
- ] + list(itertools.product(
- [
- serialization.Encoding.Raw,
- serialization.Encoding.X962,
- serialization.Encoding.PEM,
- serialization.Encoding.DER
- ],
- [
- serialization.PublicFormat.Raw,
- serialization.PublicFormat.UncompressedPoint,
- serialization.PublicFormat.CompressedPoint
- ]
- ))
+ ]
+ + list(
+ itertools.product(
+ [
+ serialization.Encoding.Raw,
+ serialization.Encoding.X962,
+ serialization.Encoding.PEM,
+ serialization.Encoding.DER,
+ ],
+ [
+ serialization.PublicFormat.Raw,
+ serialization.PublicFormat.UncompressedPoint,
+ serialization.PublicFormat.CompressedPoint,
+ ],
+ )
+ ),
)
def test_public_bytes_rejects_invalid(self, encoding, fmt, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
key = parameters.generate_private_key().public_key()
with pytest.raises(ValueError):
key.public_bytes(encoding, fmt)
def test_parameter_bytes_invalid_encoding(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
with pytest.raises(TypeError):
parameters.parameter_bytes(
- "notencoding",
- serialization.ParameterFormat.PKCS3
+ "notencoding", serialization.ParameterFormat.PKCS3
)
def test_parameter_bytes_invalid_format(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
with pytest.raises(ValueError):
- parameters.parameter_bytes(
- serialization.Encoding.PEM,
- "notformat"
- )
+ parameters.parameter_bytes(serialization.Encoding.PEM, "notformat")
def test_parameter_bytes_openssh_unsupported(self, backend):
- parameters = dh.generate_parameters(2, 512, backend)
+ parameters = FFDH3072_P.parameters(backend)
with pytest.raises(TypeError):
parameters.parameter_bytes(
serialization.Encoding.OpenSSH,
- serialization.ParameterFormat.PKCS3
+ serialization.ParameterFormat.PKCS3,
)
diff --git a/tests/hazmat/primitives/test_dsa.py b/tests/hazmat/primitives/test_dsa.py
index efd2239..bda2750 100644
--- a/tests/hazmat/primitives/test_dsa.py
+++ b/tests/hazmat/primitives/test_dsa.py
@@ -11,32 +11,33 @@
from cryptography.exceptions import AlreadyFinalized, InvalidSignature
from cryptography.hazmat.backends.interfaces import (
- DSABackend, PEMSerializationBackend
+ DSABackend,
+ PEMSerializationBackend,
)
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives.asymmetric.utils import (
- Prehashed, encode_dss_signature
+ Prehashed,
+ encode_dss_signature,
)
from cryptography.utils import CryptographyDeprecationWarning
-from .fixtures_dsa import (
- DSA_KEY_1024, DSA_KEY_2048, DSA_KEY_3072
-)
+from .fixtures_dsa import DSA_KEY_1024, DSA_KEY_2048, DSA_KEY_3072
+from .utils import skip_fips_traditional_openssl
from ...doubles import DummyHashAlgorithm, DummyKeySerializationEncryption
from ...utils import (
- load_fips_dsa_key_pair_vectors, load_fips_dsa_sig_vectors,
+ load_fips_dsa_key_pair_vectors,
+ load_fips_dsa_sig_vectors,
load_vectors_from_file,
)
def _skip_if_dsa_not_supported(backend, algorithm, p, q, g):
- if (
- not backend.dsa_parameters_supported(p, q, g) or
- not backend.dsa_hash_supported(algorithm)
- ):
+ if not backend.dsa_parameters_supported(
+ p, q, g
+ ) or not backend.dsa_hash_supported(algorithm):
pytest.skip(
- "{0} does not support the provided parameters".format(backend)
+ "{} does not support the provided parameters".format(backend)
)
@@ -49,7 +50,7 @@
@pytest.mark.requires_backend_interface(interface=DSABackend)
class TestDSA(object):
def test_generate_dsa_parameters(self, backend):
- parameters = dsa.generate_parameters(1024, backend)
+ parameters = dsa.generate_parameters(2048, backend)
assert isinstance(parameters, dsa.DSAParameters)
def test_generate_invalid_dsa_parameters(self, backend):
@@ -59,16 +60,18 @@
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join(
- "asymmetric", "DSA", "FIPS_186-3", "KeyPair.rsp"),
- load_fips_dsa_key_pair_vectors
- )
+ os.path.join("asymmetric", "DSA", "FIPS_186-3", "KeyPair.rsp"),
+ load_fips_dsa_key_pair_vectors,
+ ),
)
def test_generate_dsa_keys(self, vector, backend):
+ if (
+ backend._fips_enabled
+ and vector["p"] < backend._fips_dsa_min_modulus
+ ):
+ pytest.skip("Small modulus blocked in FIPS mode")
parameters = dsa.DSAParameterNumbers(
- p=vector['p'],
- q=vector['q'],
- g=vector['g']
+ p=vector["p"], q=vector["q"], g=vector["g"]
).parameters(backend)
skey = parameters.generate_private_key()
numbers = skey.private_numbers()
@@ -79,10 +82,10 @@
assert parameter_numbers.p == skey_parameters.p
assert parameter_numbers.q == skey_parameters.q
assert parameter_numbers.g == skey_parameters.g
- assert skey_parameters.p == vector['p']
- assert skey_parameters.q == vector['q']
- assert skey_parameters.g == vector['g']
- assert skey.key_size == vector['p'].bit_length()
+ assert skey_parameters.p == vector["p"]
+ assert skey_parameters.q == vector["q"]
+ assert skey_parameters.g == vector["g"]
+ assert skey.key_size == vector["p"].bit_length()
assert pkey.key_size == skey.key_size
public_numbers = pkey.public_numbers()
assert numbers.public_numbers.y == public_numbers.y
@@ -91,7 +94,7 @@
)
def test_generate_dsa_private_key_and_parameters(self, backend):
- skey = dsa.generate_private_key(1024, backend)
+ skey = dsa.generate_private_key(2048, backend)
assert skey
numbers = skey.private_numbers()
skey_parameters = numbers.public_numbers.parameter_numbers
@@ -130,7 +133,7 @@
(
DSA_KEY_2048.public_numbers.parameter_numbers.p,
2 ** 250,
- DSA_KEY_2048.public_numbers.parameter_numbers.g
+ DSA_KEY_2048.public_numbers.parameter_numbers.g,
),
(
DSA_KEY_3072.public_numbers.parameter_numbers.p,
@@ -140,19 +143,19 @@
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
- 0
+ 0,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
- 1
+ 1,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
- 2 ** 1200
+ 2 ** 1200,
),
- ]
+ ],
)
def test_invalid_parameters_values(self, p, q, g, backend):
with pytest.raises(ValueError):
@@ -264,17 +267,18 @@
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
2 ** 100,
- DSA_KEY_1024.x
+ DSA_KEY_1024.x,
),
- ]
+ ],
)
def test_invalid_dsa_private_key_arguments(self, p, q, g, y, x, backend):
with pytest.raises(ValueError):
dsa.DSAPrivateNumbers(
public_numbers=dsa.DSAPublicNumbers(
parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g),
- y=y
- ), x=x
+ y=y,
+ ),
+ x=x,
).private_key(backend)
@pytest.mark.parametrize(
@@ -340,72 +344,95 @@
2 ** 1200,
DSA_KEY_1024.public_numbers.y,
),
- ]
+ ],
)
def test_invalid_dsa_public_key_arguments(self, p, q, g, y, backend):
with pytest.raises(ValueError):
dsa.DSAPublicNumbers(
- parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g),
- y=y
+ parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g), y=y
).public_key(backend)
+ def test_large_p(self, backend):
+ key = load_vectors_from_file(
+ os.path.join("asymmetric", "PEM_Serialization", "dsa_4096.pem"),
+ lambda pemfile: serialization.load_pem_private_key(
+ pemfile.read(), None, backend
+ ),
+ mode="rb",
+ )
+ pn = key.private_numbers()
+ assert pn.public_numbers.parameter_numbers.p.bit_length() == 4096
+ # Turn it back into a key to confirm that values this large pass
+ # verification
+ dsa.DSAPrivateNumbers(
+ public_numbers=dsa.DSAPublicNumbers(
+ parameter_numbers=dsa.DSAParameterNumbers(
+ p=pn.public_numbers.parameter_numbers.p,
+ q=pn.public_numbers.parameter_numbers.q,
+ g=pn.public_numbers.parameter_numbers.g,
+ ),
+ y=pn.public_numbers.y,
+ ),
+ x=pn.x,
+ ).private_key(backend)
+
@pytest.mark.requires_backend_interface(interface=DSABackend)
class TestDSAVerification(object):
_algorithms_dict = {
- 'SHA1': hashes.SHA1,
- 'SHA224': hashes.SHA224,
- 'SHA256': hashes.SHA256,
- 'SHA384': hashes.SHA384,
- 'SHA512': hashes.SHA512
+ "SHA1": hashes.SHA1,
+ "SHA224": hashes.SHA224,
+ "SHA256": hashes.SHA256,
+ "SHA384": hashes.SHA384,
+ "SHA512": hashes.SHA512,
}
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join(
- "asymmetric", "DSA", "FIPS_186-3", "SigVer.rsp"),
- load_fips_dsa_sig_vectors
- )
+ os.path.join("asymmetric", "DSA", "FIPS_186-3", "SigVer.rsp"),
+ load_fips_dsa_sig_vectors,
+ ),
)
def test_dsa_verification(self, vector, backend):
- digest_algorithm = vector['digest_algorithm'].replace("-", "")
+ digest_algorithm = vector["digest_algorithm"].replace("-", "")
algorithm = self._algorithms_dict[digest_algorithm]
_skip_if_dsa_not_supported(
- backend, algorithm, vector['p'], vector['q'], vector['g']
+ backend, algorithm, vector["p"], vector["q"], vector["g"]
)
public_key = dsa.DSAPublicNumbers(
parameter_numbers=dsa.DSAParameterNumbers(
- vector['p'], vector['q'], vector['g']
+ vector["p"], vector["q"], vector["g"]
),
- y=vector['y']
+ y=vector["y"],
).public_key(backend)
- sig = encode_dss_signature(vector['r'], vector['s'])
+ sig = encode_dss_signature(vector["r"], vector["s"])
- if vector['result'] == "F":
+ if vector["result"] == "F":
with pytest.raises(InvalidSignature):
- public_key.verify(sig, vector['msg'], algorithm())
+ public_key.verify(sig, vector["msg"], algorithm())
else:
- public_key.verify(sig, vector['msg'], algorithm())
+ public_key.verify(sig, vector["msg"], algorithm())
def test_dsa_verify_invalid_asn1(self, backend):
public_key = DSA_KEY_1024.public_numbers.public_key(backend)
with pytest.raises(InvalidSignature):
- public_key.verify(b'fakesig', b'fakemsg', hashes.SHA1())
+ public_key.verify(b"fakesig", b"fakemsg", hashes.SHA1())
def test_signature_not_bytes(self, backend):
public_key = DSA_KEY_1024.public_numbers.public_key(backend)
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
public_key.verifier(1234, hashes.SHA1())
def test_use_after_finalize(self, backend):
public_key = DSA_KEY_1024.public_numbers.public_key(backend)
with pytest.warns(CryptographyDeprecationWarning):
- verifier = public_key.verifier(b'fakesig', hashes.SHA1())
- verifier.update(b'irrelevant')
+ verifier = public_key.verifier(b"fakesig", hashes.SHA1())
+ verifier.update(b"irrelevant")
with pytest.raises(InvalidSignature):
verifier.verify()
with pytest.raises(AlreadyFinalized):
@@ -445,57 +472,57 @@
def test_prehashed_unsupported_in_signer_ctx(self, backend):
private_key = DSA_KEY_1024.private_key(backend)
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
private_key.signer(Prehashed(hashes.SHA1()))
def test_prehashed_unsupported_in_verifier_ctx(self, backend):
public_key = DSA_KEY_1024.private_key(backend).public_key()
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
- public_key.verifier(
- b"0" * 64, Prehashed(hashes.SHA1())
- )
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
+ public_key.verifier(b"0" * 64, Prehashed(hashes.SHA1()))
@pytest.mark.requires_backend_interface(interface=DSABackend)
class TestDSASignature(object):
_algorithms_dict = {
- 'SHA1': hashes.SHA1,
- 'SHA224': hashes.SHA224,
- 'SHA256': hashes.SHA256,
- 'SHA384': hashes.SHA384,
- 'SHA512': hashes.SHA512}
+ "SHA1": hashes.SHA1,
+ "SHA224": hashes.SHA224,
+ "SHA256": hashes.SHA256,
+ "SHA384": hashes.SHA384,
+ "SHA512": hashes.SHA512,
+ }
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join(
- "asymmetric", "DSA", "FIPS_186-3", "SigGen.txt"),
- load_fips_dsa_sig_vectors
- )
+ os.path.join("asymmetric", "DSA", "FIPS_186-3", "SigGen.txt"),
+ load_fips_dsa_sig_vectors,
+ ),
)
def test_dsa_signing(self, vector, backend):
- digest_algorithm = vector['digest_algorithm'].replace("-", "")
+ digest_algorithm = vector["digest_algorithm"].replace("-", "")
algorithm = self._algorithms_dict[digest_algorithm]
_skip_if_dsa_not_supported(
- backend, algorithm, vector['p'], vector['q'], vector['g']
+ backend, algorithm, vector["p"], vector["q"], vector["g"]
)
private_key = dsa.DSAPrivateNumbers(
public_numbers=dsa.DSAPublicNumbers(
parameter_numbers=dsa.DSAParameterNumbers(
- vector['p'], vector['q'], vector['g']
+ vector["p"], vector["q"], vector["g"]
),
- y=vector['y']
+ y=vector["y"],
),
- x=vector['x']
+ x=vector["x"],
).private_key(backend)
- signature = private_key.sign(vector['msg'], algorithm())
+ signature = private_key.sign(vector["msg"], algorithm())
assert signature
- private_key.public_key().verify(signature, vector['msg'], algorithm())
+ private_key.public_key().verify(signature, vector["msg"], algorithm())
def test_use_after_finalize(self, backend):
private_key = DSA_KEY_1024.private_key(backend)
@@ -558,8 +585,7 @@
def test_dsa_public_numbers(self):
parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
public_numbers = dsa.DSAPublicNumbers(
- y=4,
- parameter_numbers=parameter_numbers
+ y=4, parameter_numbers=parameter_numbers
)
assert public_numbers.y == 4
assert public_numbers.parameter_numbers == parameter_numbers
@@ -575,12 +601,10 @@
def test_dsa_private_numbers(self):
parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
public_numbers = dsa.DSAPublicNumbers(
- y=4,
- parameter_numbers=parameter_numbers
+ y=4, parameter_numbers=parameter_numbers
)
private_numbers = dsa.DSAPrivateNumbers(
- x=5,
- public_numbers=public_numbers
+ x=5, public_numbers=public_numbers
)
assert private_numbers.x == 5
assert private_numbers.public_numbers == public_numbers
@@ -588,8 +612,7 @@
def test_dsa_private_numbers_invalid_types(self):
parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
public_numbers = dsa.DSAPublicNumbers(
- y=4,
- parameter_numbers=parameter_numbers
+ y=4, parameter_numbers=parameter_numbers
)
with pytest.raises(TypeError):
dsa.DSAPrivateNumbers(x=4, public_numbers=None)
@@ -604,8 +627,7 @@
)
public_numbers = dsa.DSAPublicNumbers(
- y=4,
- parameter_numbers=parameter_numbers
+ y=4, parameter_numbers=parameter_numbers
)
assert repr(public_numbers) == (
"<DSAPublicNumbers(y=4, parameter_numbers=<DSAParameterNumbers(p=1"
@@ -641,38 +663,26 @@
pub = dsa.DSAPublicNumbers(1, dsa.DSAParameterNumbers(1, 2, 3))
priv = dsa.DSAPrivateNumbers(1, pub)
assert priv == dsa.DSAPrivateNumbers(
- 1, dsa.DSAPublicNumbers(
- 1, dsa.DSAParameterNumbers(1, 2, 3)
- )
+ 1, dsa.DSAPublicNumbers(1, dsa.DSAParameterNumbers(1, 2, 3))
)
def test_private_numbers_ne(self):
pub = dsa.DSAPublicNumbers(1, dsa.DSAParameterNumbers(1, 2, 3))
priv = dsa.DSAPrivateNumbers(1, pub)
assert priv != dsa.DSAPrivateNumbers(
- 2, dsa.DSAPublicNumbers(
- 1, dsa.DSAParameterNumbers(1, 2, 3)
- )
+ 2, dsa.DSAPublicNumbers(1, dsa.DSAParameterNumbers(1, 2, 3))
)
assert priv != dsa.DSAPrivateNumbers(
- 1, dsa.DSAPublicNumbers(
- 2, dsa.DSAParameterNumbers(1, 2, 3)
- )
+ 1, dsa.DSAPublicNumbers(2, dsa.DSAParameterNumbers(1, 2, 3))
)
assert priv != dsa.DSAPrivateNumbers(
- 1, dsa.DSAPublicNumbers(
- 1, dsa.DSAParameterNumbers(2, 2, 3)
- )
+ 1, dsa.DSAPublicNumbers(1, dsa.DSAParameterNumbers(2, 2, 3))
)
assert priv != dsa.DSAPrivateNumbers(
- 1, dsa.DSAPublicNumbers(
- 1, dsa.DSAParameterNumbers(1, 3, 3)
- )
+ 1, dsa.DSAPublicNumbers(1, dsa.DSAParameterNumbers(1, 3, 3))
)
assert priv != dsa.DSAPrivateNumbers(
- 1, dsa.DSAPublicNumbers(
- 1, dsa.DSAParameterNumbers(1, 2, 4)
- )
+ 1, dsa.DSAPublicNumbers(1, dsa.DSAParameterNumbers(1, 2, 4))
)
assert priv != object()
@@ -685,26 +695,27 @@
itertools.product(
[
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.PrivateFormat.PKCS8
+ serialization.PrivateFormat.PKCS8,
],
[
b"s",
b"longerpassword",
b"!*$&(@#$*&($T@%_somesymbols",
b"\x01" * 1000,
- ]
- )
+ ],
+ ),
)
def test_private_bytes_encrypted_pem(self, backend, fmt, password):
+ skip_fips_traditional_openssl(backend, fmt)
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
- lambda pemfile: pemfile.read().encode()
+ lambda pemfile: pemfile.read().encode(),
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
serialized = key.private_bytes(
serialization.Encoding.PEM,
fmt,
- serialization.BestAvailableEncryption(password)
+ serialization.BestAvailableEncryption(password),
)
loaded_key = serialization.load_pem_private_key(
serialized, password, backend
@@ -720,7 +731,7 @@
(serialization.Encoding.DER, serialization.PrivateFormat.Raw),
(serialization.Encoding.Raw, serialization.PrivateFormat.Raw),
(serialization.Encoding.X962, serialization.PrivateFormat.PKCS8),
- ]
+ ],
)
def test_private_bytes_rejects_invalid(self, encoding, fmt, backend):
key = DSA_KEY_1024.private_key(backend)
@@ -733,19 +744,19 @@
[serialization.PrivateFormat.PKCS8, b"s"],
[serialization.PrivateFormat.PKCS8, b"longerpassword"],
[serialization.PrivateFormat.PKCS8, b"!*$&(@#$*&($T@%_somesymbol"],
- [serialization.PrivateFormat.PKCS8, b"\x01" * 1000]
- ]
+ [serialization.PrivateFormat.PKCS8, b"\x01" * 1000],
+ ],
)
def test_private_bytes_encrypted_der(self, backend, fmt, password):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
- lambda pemfile: pemfile.read().encode()
+ lambda pemfile: pemfile.read().encode(),
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
serialized = key.private_bytes(
serialization.Encoding.DER,
fmt,
- serialization.BestAvailableEncryption(password)
+ serialization.BestAvailableEncryption(password),
)
loaded_key = serialization.load_der_private_key(
serialized, password, backend
@@ -760,27 +771,28 @@
[
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
[
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
- ]
+ ],
)
- def test_private_bytes_unencrypted(self, backend, encoding, fmt,
- loader_func):
+ def test_private_bytes_unencrypted(
+ self, backend, encoding, fmt, loader_func
+ ):
key = DSA_KEY_1024.private_key(backend)
serialized = key.private_bytes(
encoding, fmt, serialization.NoEncryption()
@@ -790,6 +802,9 @@
priv_num = key.private_numbers()
assert loaded_priv_num == priv_num
+ @pytest.mark.skip_fips(
+ reason="Traditional OpenSSL key format is not supported in FIPS mode."
+ )
@pytest.mark.parametrize(
("key_path", "encoding", "loader_func"),
[
@@ -797,19 +812,19 @@
os.path.join(
"asymmetric",
"Traditional_OpenSSL_Serialization",
- "dsa.1024.pem"
+ "dsa.1024.pem",
),
serialization.Encoding.PEM,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
os.path.join(
"asymmetric", "DER_Serialization", "dsa.1024.der"
),
serialization.Encoding.DER,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
- ]
+ ],
)
def test_private_bytes_traditional_openssl_unencrypted(
self, backend, key_path, encoding, loader_func
@@ -821,7 +836,7 @@
serialized = key.private_bytes(
encoding,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
assert serialized == key_bytes
@@ -831,7 +846,7 @@
key.private_bytes(
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.BestAvailableEncryption(b"password")
+ serialization.BestAvailableEncryption(b"password"),
)
def test_private_bytes_invalid_encoding(self, backend):
@@ -839,13 +854,13 @@
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(TypeError):
key.private_bytes(
"notencoding",
serialization.PrivateFormat.PKCS8,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_format(self, backend):
@@ -853,13 +868,13 @@
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.PEM,
"invalidformat",
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_encryption_algorithm(self, backend):
@@ -867,13 +882,13 @@
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- "notanencalg"
+ "notanencalg",
)
def test_private_bytes_unsupported_encryption_type(self, backend):
@@ -881,13 +896,13 @@
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- DummyKeySerializationEncryption()
+ DummyKeySerializationEncryption(),
)
@@ -901,32 +916,36 @@
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pub.pem"),
serialization.load_pem_public_key,
serialization.Encoding.PEM,
- ), (
+ ),
+ (
os.path.join(
"asymmetric",
"DER_Serialization",
- "unenc-dsa-pkcs8.pub.der"
+ "unenc-dsa-pkcs8.pub.der",
),
serialization.load_der_public_key,
serialization.Encoding.DER,
- )
- ]
+ ),
+ ],
)
- def test_public_bytes_match(self, key_path, loader_func, encoding,
- backend):
+ def test_public_bytes_match(
+ self, key_path, loader_func, encoding, backend
+ ):
key_bytes = load_vectors_from_file(
key_path, lambda pemfile: pemfile.read(), mode="rb"
)
key = loader_func(key_bytes, backend)
serialized = key.public_bytes(
- encoding, serialization.PublicFormat.SubjectPublicKeyInfo,
+ encoding,
+ serialization.PublicFormat.SubjectPublicKeyInfo,
)
assert serialized == key_bytes
def test_public_bytes_openssh(self, backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pub.pem"),
- lambda pemfile: pemfile.read(), mode="rb"
+ lambda pemfile: pemfile.read(),
+ mode="rb",
)
key = serialization.load_pem_public_key(key_bytes, backend)
@@ -950,8 +969,7 @@
key = DSA_KEY_2048.private_key(backend).public_key()
with pytest.raises(TypeError):
key.public_bytes(
- "notencoding",
- serialization.PublicFormat.SubjectPublicKeyInfo
+ "notencoding", serialization.PublicFormat.SubjectPublicKeyInfo
)
def test_public_bytes_invalid_format(self, backend):
@@ -971,22 +989,25 @@
[
(
serialization.Encoding.Raw,
- serialization.PublicFormat.SubjectPublicKeyInfo
+ serialization.PublicFormat.SubjectPublicKeyInfo,
),
(serialization.Encoding.Raw, serialization.PublicFormat.PKCS1),
- ] + list(itertools.product(
- [
- serialization.Encoding.Raw,
- serialization.Encoding.X962,
- serialization.Encoding.PEM,
- serialization.Encoding.DER
- ],
- [
- serialization.PublicFormat.Raw,
- serialization.PublicFormat.UncompressedPoint,
- serialization.PublicFormat.CompressedPoint
- ]
- ))
+ ]
+ + list(
+ itertools.product(
+ [
+ serialization.Encoding.Raw,
+ serialization.Encoding.X962,
+ serialization.Encoding.PEM,
+ serialization.Encoding.DER,
+ ],
+ [
+ serialization.PublicFormat.Raw,
+ serialization.PublicFormat.UncompressedPoint,
+ serialization.PublicFormat.CompressedPoint,
+ ],
+ )
+ ),
)
def test_public_bytes_rejects_invalid(self, encoding, fmt, backend):
key = DSA_KEY_2048.private_key(backend).public_key()
diff --git a/tests/hazmat/primitives/test_ec.py b/tests/hazmat/primitives/test_ec.py
index 7a6d6af..8361306 100644
--- a/tests/hazmat/primitives/test_ec.py
+++ b/tests/hazmat/primitives/test_ec.py
@@ -11,23 +11,29 @@
import pytest
-from cryptography import exceptions, utils
+from cryptography import exceptions, utils, x509
from cryptography.hazmat.backends.interfaces import (
- EllipticCurveBackend, PEMSerializationBackend
+ EllipticCurveBackend,
+ PEMSerializationBackend,
)
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import (
- Prehashed, encode_dss_signature
+ Prehashed,
+ encode_dss_signature,
)
from cryptography.utils import CryptographyDeprecationWarning
from .fixtures_ec import EC_KEY_SECP384R1
+from .utils import skip_fips_traditional_openssl
from ...doubles import DummyKeySerializationEncryption
from ...utils import (
- load_fips_ecdsa_key_pair_vectors, load_fips_ecdsa_signing_vectors,
- load_kasvs_ecdh_vectors, load_nist_vectors, load_vectors_from_file,
- raises_unsupported_algorithm
+ load_fips_ecdsa_key_pair_vectors,
+ load_fips_ecdsa_signing_vectors,
+ load_kasvs_ecdh_vectors,
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
_HASH_TYPES = {
@@ -41,11 +47,10 @@
def _skip_ecdsa_vector(backend, curve_type, hash_type):
if not backend.elliptic_curve_signature_algorithm_supported(
- ec.ECDSA(hash_type()),
- curve_type()
+ ec.ECDSA(hash_type()), curve_type()
):
pytest.skip(
- "ECDSA not supported with this hash {0} and curve {1}".format(
+ "ECDSA not supported with this hash {} and curve {}.".format(
hash_type().name, curve_type().name
)
)
@@ -54,7 +59,7 @@
def _skip_curve_unsupported(backend, curve):
if not backend.elliptic_curve_supported(curve):
pytest.skip(
- "Curve {0} is not supported by this backend {1}".format(
+ "Curve {} is not supported by this backend {}".format(
curve.name, backend
)
)
@@ -65,12 +70,18 @@
algorithm, curve
):
pytest.skip(
- "Exchange with {0} curve is not supported by {1}".format(
+ "Exchange with {} curve is not supported by {}".format(
curve.name, backend
)
)
+def test_get_curve_for_oid():
+ assert ec.get_curve_for_oid(ec.EllipticCurveOID.SECP256R1) == ec.SECP256R1
+ with pytest.raises(LookupError):
+ ec.get_curve_for_oid(x509.ObjectIdentifier("1.1.1.1"))
+
+
@utils.register_interface(ec.EllipticCurve)
class DummyCurve(object):
name = "dummy-curve"
@@ -120,10 +131,10 @@
_skip_curve_unsupported(backend, curve)
with pytest.raises(TypeError):
- ec.derive_private_key('one', curve, backend)
+ ec.derive_private_key("one", curve, backend)
with pytest.raises(TypeError):
- ec.derive_private_key(10, 'five', backend)
+ ec.derive_private_key(10, "five", backend)
with pytest.raises(ValueError):
ec.derive_private_key(-7, curve, backend)
@@ -131,10 +142,7 @@
def test_ec_numbers():
numbers = ec.EllipticCurvePrivateNumbers(
- 1,
- ec.EllipticCurvePublicNumbers(
- 2, 3, DummyCurve()
- )
+ 1, ec.EllipticCurvePublicNumbers(2, 3, DummyCurve())
)
assert numbers.private_value == 1
@@ -150,7 +158,7 @@
(1, None, 3, DummyCurve()),
(1, 2, None, DummyCurve()),
(1, 2, 3, None),
- ]
+ ],
)
def test_invalid_ec_numbers_args(private_value, x, y, curve):
with pytest.raises(TypeError):
@@ -167,15 +175,13 @@
def test_encode_point():
# secp256r1 point
x = int(
- '233ea3b0027127084cd2cd336a13aeef69c598d8af61369a36454a17c6c22aec',
- 16
+ "233ea3b0027127084cd2cd336a13aeef69c598d8af61369a36454a17c6c22aec", 16
)
y = int(
- '3ea2c10a84153862be4ec82940f0543f9ba866af9751a6ee79d38460b35f442e',
- 16
+ "3ea2c10a84153862be4ec82940f0543f9ba866af9751a6ee79d38460b35f442e", 16
)
pn = ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1())
- with pytest.warns(utils.DeprecatedIn25):
+ with pytest.warns(utils.PersistentlyDeprecated2019):
data = pn.encode_point()
assert data == binascii.unhexlify(
"04233ea3b0027127084cd2cd336a13aeef69c598d8af61369a36454a17c6c22ae"
@@ -194,12 +200,10 @@
ec.SECP256R1(), data
)
assert pn.x == int(
- '233ea3b0027127084cd2cd336a13aeef69c598d8af61369a36454a17c6c22aec',
- 16
+ "233ea3b0027127084cd2cd336a13aeef69c598d8af61369a36454a17c6c22aec", 16
)
assert pn.y == int(
- '3ea2c10a84153862be4ec82940f0543f9ba866af9751a6ee79d38460b35f442e',
- 16
+ "3ea2c10a84153862be4ec82940f0543f9ba866af9751a6ee79d38460b35f442e", 16
)
@@ -277,34 +281,35 @@
class TestECWithNumbers(object):
@pytest.mark.parametrize(
("vector", "hash_type"),
- list(itertools.product(
- load_vectors_from_file(
- os.path.join(
- "asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp"),
- load_fips_ecdsa_key_pair_vectors
- ),
- _HASH_TYPES.values()
- ))
+ list(
+ itertools.product(
+ load_vectors_from_file(
+ os.path.join(
+ "asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp"
+ ),
+ load_fips_ecdsa_key_pair_vectors,
+ ),
+ _HASH_TYPES.values(),
+ )
+ ),
)
def test_with_numbers(self, backend, vector, hash_type):
- curve_type = ec._CURVE_TYPES[vector['curve']]
+ curve_type = ec._CURVE_TYPES[vector["curve"]]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePrivateNumbers(
- vector['d'],
+ vector["d"],
ec.EllipticCurvePublicNumbers(
- vector['x'],
- vector['y'],
- curve_type()
- )
+ vector["x"], vector["y"], curve_type()
+ ),
).private_key(backend)
assert key
priv_num = key.private_numbers()
- assert priv_num.private_value == vector['d']
- assert priv_num.public_numbers.x == vector['x']
- assert priv_num.public_numbers.y == vector['y']
+ assert priv_num.private_value == vector["d"]
+ assert priv_num.public_numbers.x == vector["x"]
+ assert priv_num.public_numbers.y == vector["y"]
assert curve_type().name == priv_num.public_numbers.curve.name
@@ -312,27 +317,28 @@
class TestECDSAVectors(object):
@pytest.mark.parametrize(
("vector", "hash_type"),
- list(itertools.product(
- load_vectors_from_file(
- os.path.join(
- "asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp"),
- load_fips_ecdsa_key_pair_vectors
- ),
- _HASH_TYPES.values()
- ))
+ list(
+ itertools.product(
+ load_vectors_from_file(
+ os.path.join(
+ "asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp"
+ ),
+ load_fips_ecdsa_key_pair_vectors,
+ ),
+ _HASH_TYPES.values(),
+ )
+ ),
)
def test_signing_with_example_keys(self, backend, vector, hash_type):
- curve_type = ec._CURVE_TYPES[vector['curve']]
+ curve_type = ec._CURVE_TYPES[vector["curve"]]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePrivateNumbers(
- vector['d'],
+ vector["d"],
ec.EllipticCurvePublicNumbers(
- vector['x'],
- vector['y'],
- curve_type()
- )
+ vector["x"], vector["y"], curve_type()
+ ),
).private_key(backend)
assert key
@@ -349,9 +355,7 @@
verifier.update(b"YELLOW SUBMARINE")
verifier.verify()
- @pytest.mark.parametrize(
- "curve", ec._CURVE_TYPES.values()
- )
+ @pytest.mark.parametrize("curve", ec._CURVE_TYPES.values())
def test_generate_vector_curves(self, backend, curve):
_skip_curve_unsupported(backend, curve())
@@ -371,10 +375,12 @@
):
ec.generate_private_key(DummyCurve(), backend)
- assert backend.elliptic_curve_signature_algorithm_supported(
- ec.ECDSA(hashes.SHA256()),
- DummyCurve()
- ) is False
+ assert (
+ backend.elliptic_curve_signature_algorithm_supported(
+ ec.ECDSA(hashes.SHA256()), DummyCurve()
+ )
+ is False
+ )
def test_unknown_signature_algoritm(self, backend):
_skip_curve_unsupported(backend, ec.SECP192R1())
@@ -403,10 +409,12 @@
b"signature", b"data", DummySignatureAlgorithm()
)
- assert backend.elliptic_curve_signature_algorithm_supported(
- DummySignatureAlgorithm(),
- ec.SECP192R1()
- ) is False
+ assert (
+ backend.elliptic_curve_signature_algorithm_supported(
+ DummySignatureAlgorithm(), ec.SECP192R1()
+ )
+ is False
+ )
def test_load_invalid_ec_key_from_numbers(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
@@ -417,7 +425,7 @@
47250808410327023131573602008345894927686381772325561185532964,
1120253292479243545483756778742719537373113335231773536789915,
ec.SECP256R1(),
- )
+ ),
)
with pytest.raises(ValueError):
numbers.private_key(backend)
@@ -428,7 +436,7 @@
-4725080841032702313157360200834589492768638177232556118553296,
1120253292479243545483756778742719537373113335231773536789915,
ec.SECP256R1(),
- )
+ ),
)
with pytest.raises(ValueError):
numbers.private_key(backend)
@@ -439,7 +447,7 @@
47250808410327023131573602008345894927686381772325561185532964,
-1120253292479243545483756778742719537373113335231773536789915,
ec.SECP256R1(),
- )
+ ),
)
with pytest.raises(ValueError):
numbers.private_key(backend)
@@ -449,26 +457,38 @@
# Bad X coordinate
numbers = ec.EllipticCurvePublicNumbers(
- int("000003647356b91f8ace114c7247ecf4f4a622553fc025e04a178f179ef27"
+ int(
+ "000003647356b91f8ace114c7247ecf4f4a622553fc025e04a178f179ef27"
"9090c184af678a4c78f635483bdd8aa544851c6ef291c1f0d6a241ebfd145"
- "77d1d30d9903ce", 16),
- int("000001499bc7e079322ea0fcfbd6b40103fa6a1536c2257b182db0df4b369"
+ "77d1d30d9903ce",
+ 16,
+ ),
+ int(
+ "000001499bc7e079322ea0fcfbd6b40103fa6a1536c2257b182db0df4b369"
"6ec643adf100eb4f2025d1b873f82e5a475d6e4400ba777090eeb4563a115"
- "09e4c87319dc26", 16),
- ec.SECP521R1()
+ "09e4c87319dc26",
+ 16,
+ ),
+ ec.SECP521R1(),
)
with pytest.raises(ValueError):
numbers.public_key(backend)
# Bad Y coordinate
numbers = ec.EllipticCurvePublicNumbers(
- int("0000019aadc221cc0525118ab6d5aa1f64720603de0be128cbfea0b381ad8"
+ int(
+ "0000019aadc221cc0525118ab6d5aa1f64720603de0be128cbfea0b381ad8"
"02a2facc6370bb58cf88b3f0c692bc654ee19d6cad198f10d4b681b396f20"
- "d2e40603fa945b", 16),
- int("0000025da392803a320717a08d4cb3dea932039badff363b71bdb8064e726"
+ "d2e40603fa945b",
+ 16,
+ ),
+ int(
+ "0000025da392803a320717a08d4cb3dea932039badff363b71bdb8064e726"
"6c7f4f4b748d4d425347fc33e3885d34b750fa7fcd5691f4d90c89522ce33"
- "feff5db10088a5", 16),
- ec.SECP521R1()
+ "feff5db10088a5",
+ 16,
+ ),
+ ec.SECP521R1(),
)
with pytest.raises(ValueError):
numbers.public_key(backend)
@@ -478,71 +498,54 @@
itertools.chain(
load_vectors_from_file(
os.path.join(
- "asymmetric", "ECDSA", "FIPS_186-3", "SigGen.txt"),
- load_fips_ecdsa_signing_vectors
+ "asymmetric", "ECDSA", "FIPS_186-3", "SigGen.txt"
+ ),
+ load_fips_ecdsa_signing_vectors,
),
load_vectors_from_file(
- os.path.join(
- "asymmetric", "ECDSA", "SECP256K1", "SigGen.txt"),
- load_fips_ecdsa_signing_vectors
+ os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt"),
+ load_fips_ecdsa_signing_vectors,
),
- )
+ ),
)
def test_signatures(self, backend, vector):
- hash_type = _HASH_TYPES[vector['digest_algorithm']]
- curve_type = ec._CURVE_TYPES[vector['curve']]
+ hash_type = _HASH_TYPES[vector["digest_algorithm"]]
+ curve_type = ec._CURVE_TYPES[vector["curve"]]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePublicNumbers(
- vector['x'],
- vector['y'],
- curve_type()
+ vector["x"], vector["y"], curve_type()
).public_key(backend)
- signature = encode_dss_signature(vector['r'], vector['s'])
+ signature = encode_dss_signature(vector["r"], vector["s"])
- key.verify(
- signature,
- vector['message'],
- ec.ECDSA(hash_type())
- )
+ key.verify(signature, vector["message"], ec.ECDSA(hash_type()))
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
- os.path.join(
- "asymmetric", "ECDSA", "FIPS_186-3", "SigVer.rsp"),
- load_fips_ecdsa_signing_vectors
- )
+ os.path.join("asymmetric", "ECDSA", "FIPS_186-3", "SigVer.rsp"),
+ load_fips_ecdsa_signing_vectors,
+ ),
)
def test_signature_failures(self, backend, vector):
- hash_type = _HASH_TYPES[vector['digest_algorithm']]
- curve_type = ec._CURVE_TYPES[vector['curve']]
+ hash_type = _HASH_TYPES[vector["digest_algorithm"]]
+ curve_type = ec._CURVE_TYPES[vector["curve"]]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePublicNumbers(
- vector['x'],
- vector['y'],
- curve_type()
+ vector["x"], vector["y"], curve_type()
).public_key(backend)
- signature = encode_dss_signature(vector['r'], vector['s'])
+ signature = encode_dss_signature(vector["r"], vector["s"])
if vector["fail"] is True:
with pytest.raises(exceptions.InvalidSignature):
- key.verify(
- signature,
- vector['message'],
- ec.ECDSA(hash_type())
- )
+ key.verify(signature, vector["message"], ec.ECDSA(hash_type()))
else:
- key.verify(
- signature,
- vector['message'],
- ec.ECDSA(hash_type())
- )
+ key.verify(signature, vector["message"], ec.ECDSA(hash_type()))
def test_sign(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
@@ -595,9 +598,7 @@
h.update(message)
data = h.finalize()
public_key = private_key.public_key()
- public_key.verify(
- signature, data, ec.ECDSA(Prehashed(hashes.SHA1()))
- )
+ public_key.verify(signature, data, ec.ECDSA(Prehashed(hashes.SHA1())))
def test_verify_prehashed_digest_mismatch(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
@@ -615,20 +616,19 @@
def test_prehashed_unsupported_in_signer_ctx(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
private_key.signer(ec.ECDSA(Prehashed(hashes.SHA1())))
def test_prehashed_unsupported_in_verifier_ctx(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
public_key = private_key.public_key()
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
- public_key.verifier(
- b"0" * 64,
- ec.ECDSA(Prehashed(hashes.SHA1()))
- )
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
+ public_key.verifier(b"0" * 64, ec.ECDSA(Prehashed(hashes.SHA1())))
class TestECNumbersEquality(object):
@@ -676,28 +676,28 @@
itertools.product(
[
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.PrivateFormat.PKCS8
+ serialization.PrivateFormat.PKCS8,
],
[
b"s",
b"longerpassword",
b"!*$&(@#$*&($T@%_somesymbols",
b"\x01" * 1000,
- ]
- )
+ ],
+ ),
)
def test_private_bytes_encrypted_pem(self, backend, fmt, password):
+ skip_fips_traditional_openssl(backend, fmt)
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
- lambda pemfile: pemfile.read().encode()
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
+ lambda pemfile: pemfile.read().encode(),
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
serialized = key.private_bytes(
serialization.Encoding.PEM,
fmt,
- serialization.BestAvailableEncryption(password)
+ serialization.BestAvailableEncryption(password),
)
loaded_key = serialization.load_pem_private_key(
serialized, password, backend
@@ -713,7 +713,7 @@
(serialization.Encoding.DER, serialization.PrivateFormat.Raw),
(serialization.Encoding.Raw, serialization.PrivateFormat.Raw),
(serialization.Encoding.X962, serialization.PrivateFormat.PKCS8),
- ]
+ ],
)
def test_private_bytes_rejects_invalid(self, encoding, fmt, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
@@ -727,21 +727,20 @@
[serialization.PrivateFormat.PKCS8, b"s"],
[serialization.PrivateFormat.PKCS8, b"longerpassword"],
[serialization.PrivateFormat.PKCS8, b"!*$&(@#$*&($T@%_somesymbol"],
- [serialization.PrivateFormat.PKCS8, b"\x01" * 1000]
- ]
+ [serialization.PrivateFormat.PKCS8, b"\x01" * 1000],
+ ],
)
def test_private_bytes_encrypted_der(self, backend, fmt, password):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
- lambda pemfile: pemfile.read().encode()
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
+ lambda pemfile: pemfile.read().encode(),
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
serialized = key.private_bytes(
serialization.Encoding.DER,
fmt,
- serialization.BestAvailableEncryption(password)
+ serialization.BestAvailableEncryption(password),
)
loaded_key = serialization.load_der_private_key(
serialized, password, backend
@@ -756,32 +755,32 @@
[
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
[
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
- ]
+ ],
)
- def test_private_bytes_unencrypted(self, backend, encoding, fmt,
- loader_func):
+ def test_private_bytes_unencrypted(
+ self, backend, encoding, fmt, loader_func
+ ):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
- lambda pemfile: pemfile.read().encode()
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
+ lambda pemfile: pemfile.read().encode(),
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
serialized = key.private_bytes(
@@ -792,6 +791,9 @@
priv_num = key.private_numbers()
assert loaded_priv_num == priv_num
+ @pytest.mark.skip_fips(
+ reason="Traditional OpenSSL key format is not supported in FIPS mode."
+ )
@pytest.mark.parametrize(
("key_path", "encoding", "loader_func"),
[
@@ -800,16 +802,16 @@
"asymmetric", "PEM_Serialization", "ec_private_key.pem"
),
serialization.Encoding.PEM,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
os.path.join(
"asymmetric", "DER_Serialization", "ec_private_key.der"
),
serialization.Encoding.DER,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
- ]
+ ],
)
def test_private_bytes_traditional_openssl_unencrypted(
self, backend, key_path, encoding, loader_func
@@ -822,103 +824,97 @@
serialized = key.private_bytes(
encoding,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
assert serialized == key_bytes
def test_private_bytes_traditional_der_encrypted_invalid(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.BestAvailableEncryption(b"password")
+ serialization.BestAvailableEncryption(b"password"),
)
def test_private_bytes_invalid_encoding(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(TypeError):
key.private_bytes(
"notencoding",
serialization.PrivateFormat.PKCS8,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_format(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.PEM,
"invalidformat",
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_encryption_algorithm(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- "notanencalg"
+ "notanencalg",
)
def test_private_bytes_unsupported_encryption_type(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- DummyKeySerializationEncryption()
+ DummyKeySerializationEncryption(),
)
def test_public_bytes_from_derived_public_key(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
public = key.public_key()
pem = public.public_bytes(
serialization.Encoding.PEM,
- serialization.PublicFormat.SubjectPublicKeyInfo
+ serialization.PublicFormat.SubjectPublicKeyInfo,
)
parsed_public = serialization.load_pem_public_key(pem, backend)
assert parsed_public
@@ -936,24 +932,27 @@
),
serialization.load_pem_public_key,
serialization.Encoding.PEM,
- ), (
+ ),
+ (
os.path.join(
"asymmetric", "DER_Serialization", "ec_public_key.der"
),
serialization.load_der_public_key,
serialization.Encoding.DER,
- )
- ]
+ ),
+ ],
)
- def test_public_bytes_match(self, key_path, loader_func, encoding,
- backend):
+ def test_public_bytes_match(
+ self, key_path, loader_func, encoding, backend
+ ):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
key_path, lambda pemfile: pemfile.read(), mode="rb"
)
key = loader_func(key_bytes, backend)
serialized = key.public_bytes(
- encoding, serialization.PublicFormat.SubjectPublicKeyInfo,
+ encoding,
+ serialization.PublicFormat.SubjectPublicKeyInfo,
)
assert serialized == key_bytes
@@ -965,7 +964,8 @@
os.path.join(
"asymmetric", "PEM_Serialization", "ec_public_key.pem"
),
- lambda pemfile: pemfile.read(), mode="rb"
+ lambda pemfile: pemfile.read(),
+ mode="rb",
)
key = serialization.load_pem_public_key(key_bytes, backend)
@@ -982,7 +982,7 @@
with pytest.raises(ValueError):
key.public_bytes(
serialization.Encoding.OpenSSH,
- serialization.PublicFormat.OpenSSH
+ serialization.PublicFormat.OpenSSH,
)
def test_public_bytes_invalid_encoding(self, backend):
@@ -993,35 +993,37 @@
),
lambda pemfile: serialization.load_pem_public_key(
pemfile.read().encode(), backend
- )
+ ),
)
with pytest.raises(TypeError):
key.public_bytes(
- "notencoding",
- serialization.PublicFormat.SubjectPublicKeyInfo
+ "notencoding", serialization.PublicFormat.SubjectPublicKeyInfo
)
@pytest.mark.parametrize(
("encoding", "fmt"),
- list(itertools.product(
- [
- serialization.Encoding.Raw,
- serialization.Encoding.X962,
- serialization.Encoding.PEM,
- serialization.Encoding.DER
- ],
- [
- serialization.PublicFormat.Raw,
- ]
- )) + list(itertools.product(
- [serialization.Encoding.Raw],
- [
- serialization.PublicFormat.SubjectPublicKeyInfo,
- serialization.PublicFormat.PKCS1,
- serialization.PublicFormat.UncompressedPoint,
- serialization.PublicFormat.CompressedPoint,
- ]
- ))
+ list(
+ itertools.product(
+ [
+ serialization.Encoding.Raw,
+ serialization.Encoding.X962,
+ serialization.Encoding.PEM,
+ serialization.Encoding.DER,
+ ],
+ [serialization.PublicFormat.Raw],
+ )
+ )
+ + list(
+ itertools.product(
+ [serialization.Encoding.Raw],
+ [
+ serialization.PublicFormat.SubjectPublicKeyInfo,
+ serialization.PublicFormat.PKCS1,
+ serialization.PublicFormat.UncompressedPoint,
+ serialization.PublicFormat.CompressedPoint,
+ ],
+ )
+ ),
)
def test_public_bytes_rejects_invalid(self, encoding, fmt, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
@@ -1037,7 +1039,7 @@
),
lambda pemfile: serialization.load_pem_public_key(
pemfile.read().encode(), backend
- )
+ ),
)
with pytest.raises(TypeError):
key.public_bytes(serialization.Encoding.PEM, "invalidformat")
@@ -1050,7 +1052,7 @@
),
lambda pemfile: serialization.load_pem_public_key(
pemfile.read().encode(), backend
- )
+ ),
)
with pytest.raises(ValueError):
key.public_bytes(
@@ -1061,14 +1063,14 @@
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "EC", "compressed_points.txt"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
- def test_from_encoded_point_compressed(self, vector):
- curve = {
- b"SECP256R1": ec.SECP256R1(),
- b"SECP256K1": ec.SECP256K1(),
- }[vector["curve"]]
+ def test_from_encoded_point_compressed(self, vector, backend):
+ curve = {b"SECP256R1": ec.SECP256R1(), b"SECP256K1": ec.SECP256K1()}[
+ vector["curve"]
+ ]
+ _skip_curve_unsupported(backend, curve)
point = binascii.unhexlify(vector["point"])
pn = ec.EllipticCurvePublicKey.from_encoded_point(curve, point)
public_num = pn.public_numbers()
@@ -1096,12 +1098,12 @@
ec.SECP256R1(), uncompressed_point
)
assert pn.public_numbers().x == int(
- '7399336a9edf2197c2f8eb3d39aed9c34a66e45d918a07dc7684c42c9b37ac68',
- 16
+ "7399336a9edf2197c2f8eb3d39aed9c34a66e45d918a07dc7684c42c9b37ac68",
+ 16,
)
assert pn.public_numbers().y == int(
- '6699ececc4f5f0d756d3c450708a0694eb0a07a68b805070b40b058d27271f6d',
- 16
+ "6699ececc4f5f0d756d3c450708a0694eb0a07a68b805070b40b058d27271f6d",
+ 16,
)
def test_from_encoded_point_invalid_length(self):
@@ -1117,9 +1119,7 @@
def test_from_encoded_point_empty_byte_string(self):
with pytest.raises(ValueError):
- ec.EllipticCurvePublicKey.from_encoded_point(
- ec.SECP384R1(), b""
- )
+ ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP384R1(), b"")
def test_from_encoded_point_not_a_curve(self):
with pytest.raises(TypeError):
@@ -1141,31 +1141,37 @@
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "EC", "compressed_points.txt"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_serialize_point(self, vector, backend):
- curve = {
- b"SECP256R1": ec.SECP256R1(),
- b"SECP256K1": ec.SECP256K1(),
- }[vector["curve"]]
+ curve = {b"SECP256R1": ec.SECP256R1(), b"SECP256K1": ec.SECP256K1()}[
+ vector["curve"]
+ ]
+ _skip_curve_unsupported(backend, curve)
point = binascii.unhexlify(vector["point"])
key = ec.EllipticCurvePublicKey.from_encoded_point(curve, point)
key2 = ec.EllipticCurvePublicKey.from_encoded_point(
curve,
key.public_bytes(
serialization.Encoding.X962,
- serialization.PublicFormat.UncompressedPoint
- )
+ serialization.PublicFormat.UncompressedPoint,
+ ),
)
- assert key.public_bytes(
- serialization.Encoding.X962,
- serialization.PublicFormat.CompressedPoint
- ) == point
- assert key2.public_bytes(
- serialization.Encoding.X962,
- serialization.PublicFormat.CompressedPoint
- ) == point
+ assert (
+ key.public_bytes(
+ serialization.Encoding.X962,
+ serialization.PublicFormat.CompressedPoint,
+ )
+ == point
+ )
+ assert (
+ key2.public_bytes(
+ serialization.Encoding.X962,
+ serialization.PublicFormat.CompressedPoint,
+ )
+ == point
+ )
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
@@ -1174,8 +1180,9 @@
_skip_curve_unsupported(backend, ec.SECP256R1())
key = ec.generate_private_key(ec.SECP256R1(), backend)
public_key = key.public_key()
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
public_key.verifier(1234, ec.ECDSA(hashes.SHA256()))
@@ -1185,43 +1192,45 @@
"vector",
load_vectors_from_file(
os.path.join(
- "asymmetric", "ECDH",
- "KASValidityTest_ECCStaticUnified_NOKC_ZZOnly_init.fax"),
- load_kasvs_ecdh_vectors
- )
+ "asymmetric",
+ "ECDH",
+ "KASValidityTest_ECCStaticUnified_NOKC_ZZOnly_init.fax",
+ ),
+ load_kasvs_ecdh_vectors,
+ ),
)
def test_key_exchange_with_vectors(self, backend, vector):
_skip_exchange_algorithm_unsupported(
- backend, ec.ECDH(), ec._CURVE_TYPES[vector['curve']]
+ backend, ec.ECDH(), ec._CURVE_TYPES[vector["curve"]]
)
- key_numbers = vector['IUT']
+ key_numbers = vector["IUT"]
private_numbers = ec.EllipticCurvePrivateNumbers(
- key_numbers['d'],
+ key_numbers["d"],
ec.EllipticCurvePublicNumbers(
- key_numbers['x'],
- key_numbers['y'],
- ec._CURVE_TYPES[vector['curve']]()
- )
+ key_numbers["x"],
+ key_numbers["y"],
+ ec._CURVE_TYPES[vector["curve"]](),
+ ),
)
# Errno 5-7 indicates a bad public or private key, this doesn't test
# the ECDH code at all
- if vector['fail'] and vector['errno'] in [5, 6, 7]:
+ if vector["fail"] and vector["errno"] in [5, 6, 7]:
with pytest.raises(ValueError):
private_numbers.private_key(backend)
return
else:
private_key = private_numbers.private_key(backend)
- peer_numbers = vector['CAVS']
+ peer_numbers = vector["CAVS"]
public_numbers = ec.EllipticCurvePublicNumbers(
- peer_numbers['x'],
- peer_numbers['y'],
- ec._CURVE_TYPES[vector['curve']]()
+ peer_numbers["x"],
+ peer_numbers["y"],
+ ec._CURVE_TYPES[vector["curve"]](),
)
# Errno 1 and 2 indicates a bad public key, this doesn't test the ECDH
# code at all
- if vector['fail'] and vector['errno'] in [1, 2]:
+ if vector["fail"] and vector["errno"] in [1, 2]:
with pytest.raises(ValueError):
public_numbers.public_key(backend)
return
@@ -1229,37 +1238,37 @@
peer_pubkey = public_numbers.public_key(backend)
z = private_key.exchange(ec.ECDH(), peer_pubkey)
- z = int(hexlify(z).decode('ascii'), 16)
+ z = int(hexlify(z).decode("ascii"), 16)
# At this point fail indicates that one of the underlying keys was
# changed. This results in a non-matching derived key.
- if vector['fail']:
+ if vector["fail"]:
# Errno 8 indicates Z should be changed.
- assert vector['errno'] == 8
- assert z != vector['Z']
+ assert vector["errno"] == 8
+ assert z != vector["Z"]
else:
- assert z == vector['Z']
+ assert z == vector["Z"]
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "ECDH", "brainpool.txt"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_brainpool_kex(self, backend, vector):
- curve = ec._CURVE_TYPES[vector['curve'].decode('ascii')]
+ curve = ec._CURVE_TYPES[vector["curve"].decode("ascii")]
_skip_exchange_algorithm_unsupported(backend, ec.ECDH(), curve)
key = ec.EllipticCurvePrivateNumbers(
- int(vector['da'], 16),
+ int(vector["da"], 16),
ec.EllipticCurvePublicNumbers(
- int(vector['x_qa'], 16), int(vector['y_qa'], 16), curve()
- )
+ int(vector["x_qa"], 16), int(vector["y_qa"], 16), curve()
+ ),
).private_key(backend)
peer = ec.EllipticCurvePrivateNumbers(
- int(vector['db'], 16),
+ int(vector["db"], 16),
ec.EllipticCurvePublicNumbers(
- int(vector['x_qb'], 16), int(vector['y_qb'], 16), curve()
- )
+ int(vector["x_qb"], 16), int(vector["y_qb"], 16), curve()
+ ),
).private_key(backend)
shared_secret = key.exchange(ec.ECDH(), peer.public_key())
assert shared_secret == binascii.unhexlify(vector["x_z"])
@@ -1270,11 +1279,10 @@
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
with raises_unsupported_algorithm(
@@ -1287,11 +1295,10 @@
_skip_curve_unsupported(backend, ec.SECP384R1())
key = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "ec_private_key.pem"),
+ os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
public_key = EC_KEY_SECP384R1.public_numbers.public_key(backend)
diff --git a/tests/hazmat/primitives/test_ed25519.py b/tests/hazmat/primitives/test_ed25519.py
new file mode 100644
index 0000000..5b003d1
--- /dev/null
+++ b/tests/hazmat/primitives/test_ed25519.py
@@ -0,0 +1,232 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from __future__ import absolute_import, division, print_function
+
+import binascii
+import os
+
+import pytest
+
+from cryptography.exceptions import InvalidSignature, _Reasons
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric.ed25519 import (
+ Ed25519PrivateKey,
+ Ed25519PublicKey,
+)
+
+from ...utils import load_vectors_from_file, raises_unsupported_algorithm
+
+
+def load_ed25519_vectors(vector_data):
+ """
+ djb's ed25519 vectors are structured as a colon delimited array:
+ 0: secret key (32 bytes) + public key (32 bytes)
+ 1: public key (32 bytes)
+ 2: message (0+ bytes)
+ 3: signature + message (64+ bytes)
+ """
+ data = []
+ for line in vector_data:
+ secret_key, public_key, message, signature, _ = line.split(":")
+ secret_key = secret_key[0:64]
+ signature = signature[0:128]
+ data.append(
+ {
+ "secret_key": secret_key,
+ "public_key": public_key,
+ "message": message,
+ "signature": signature,
+ }
+ )
+ return data
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: not backend.ed25519_supported(),
+ skip_message="Requires OpenSSL without Ed25519 support",
+)
+def test_ed25519_unsupported(backend):
+ with raises_unsupported_algorithm(
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
+ ):
+ Ed25519PublicKey.from_public_bytes(b"0" * 32)
+
+ with raises_unsupported_algorithm(
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
+ ):
+ Ed25519PrivateKey.from_private_bytes(b"0" * 32)
+
+ with raises_unsupported_algorithm(
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
+ ):
+ Ed25519PrivateKey.generate()
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: backend.ed25519_supported(),
+ skip_message="Requires OpenSSL with Ed25519 support",
+)
+class TestEd25519Signing(object):
+ @pytest.mark.parametrize(
+ "vector",
+ load_vectors_from_file(
+ os.path.join("asymmetric", "Ed25519", "sign.input"),
+ load_ed25519_vectors,
+ ),
+ )
+ def test_sign_verify_input(self, vector, backend):
+ sk = binascii.unhexlify(vector["secret_key"])
+ pk = binascii.unhexlify(vector["public_key"])
+ message = binascii.unhexlify(vector["message"])
+ signature = binascii.unhexlify(vector["signature"])
+ private_key = Ed25519PrivateKey.from_private_bytes(sk)
+ computed_sig = private_key.sign(message)
+ assert computed_sig == signature
+ public_key = private_key.public_key()
+ assert (
+ public_key.public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == pk
+ )
+ public_key.verify(signature, message)
+
+ def test_invalid_signature(self, backend):
+ key = Ed25519PrivateKey.generate()
+ signature = key.sign(b"test data")
+ with pytest.raises(InvalidSignature):
+ key.public_key().verify(signature, b"wrong data")
+
+ with pytest.raises(InvalidSignature):
+ key.public_key().verify(b"0" * 64, b"test data")
+
+ def test_generate(self, backend):
+ key = Ed25519PrivateKey.generate()
+ assert key
+ assert key.public_key()
+
+ def test_load_public_bytes(self, backend):
+ public_key = Ed25519PrivateKey.generate().public_key()
+ public_bytes = public_key.public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ public_key2 = Ed25519PublicKey.from_public_bytes(public_bytes)
+ assert public_bytes == public_key2.public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+
+ def test_invalid_type_public_bytes(self, backend):
+ with pytest.raises(TypeError):
+ Ed25519PublicKey.from_public_bytes(object())
+
+ def test_invalid_type_private_bytes(self, backend):
+ with pytest.raises(TypeError):
+ Ed25519PrivateKey.from_private_bytes(object())
+
+ def test_invalid_length_from_public_bytes(self, backend):
+ with pytest.raises(ValueError):
+ Ed25519PublicKey.from_public_bytes(b"a" * 31)
+ with pytest.raises(ValueError):
+ Ed25519PublicKey.from_public_bytes(b"a" * 33)
+
+ def test_invalid_length_from_private_bytes(self, backend):
+ with pytest.raises(ValueError):
+ Ed25519PrivateKey.from_private_bytes(b"a" * 31)
+ with pytest.raises(ValueError):
+ Ed25519PrivateKey.from_private_bytes(b"a" * 33)
+
+ def test_invalid_private_bytes(self, backend):
+ key = Ed25519PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ None,
+ )
+
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.PKCS8,
+ None,
+ )
+
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+
+ def test_invalid_public_bytes(self, backend):
+ key = Ed25519PrivateKey.generate().public_key()
+ with pytest.raises(ValueError):
+ key.public_bytes(
+ serialization.Encoding.Raw,
+ serialization.PublicFormat.SubjectPublicKeyInfo,
+ )
+
+ with pytest.raises(ValueError):
+ key.public_bytes(
+ serialization.Encoding.PEM, serialization.PublicFormat.PKCS1
+ )
+
+ with pytest.raises(ValueError):
+ key.public_bytes(
+ serialization.Encoding.PEM, serialization.PublicFormat.Raw
+ )
+
+ @pytest.mark.parametrize(
+ ("encoding", "fmt", "encryption", "passwd", "load_func"),
+ [
+ (
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.BestAvailableEncryption(b"password"),
+ b"password",
+ serialization.load_pem_private_key,
+ ),
+ (
+ serialization.Encoding.DER,
+ serialization.PrivateFormat.PKCS8,
+ serialization.BestAvailableEncryption(b"password"),
+ b"password",
+ serialization.load_der_private_key,
+ ),
+ (
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ None,
+ serialization.load_pem_private_key,
+ ),
+ (
+ serialization.Encoding.DER,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ None,
+ serialization.load_der_private_key,
+ ),
+ ],
+ )
+ def test_round_trip_private_serialization(
+ self, encoding, fmt, encryption, passwd, load_func, backend
+ ):
+ key = Ed25519PrivateKey.generate()
+ serialized = key.private_bytes(encoding, fmt, encryption)
+ loaded_key = load_func(serialized, passwd, backend)
+ assert isinstance(loaded_key, Ed25519PrivateKey)
+
+ def test_buffer_protocol(self, backend):
+ private_bytes = os.urandom(32)
+ key = Ed25519PrivateKey.from_private_bytes(bytearray(private_bytes))
+ assert (
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+ == private_bytes
+ )
diff --git a/tests/hazmat/primitives/test_ed448.py b/tests/hazmat/primitives/test_ed448.py
new file mode 100644
index 0000000..9a1f905
--- /dev/null
+++ b/tests/hazmat/primitives/test_ed448.py
@@ -0,0 +1,256 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from __future__ import absolute_import, division, print_function
+
+import binascii
+import os
+
+import pytest
+
+from cryptography.exceptions import InvalidSignature, _Reasons
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric.ed448 import (
+ Ed448PrivateKey,
+ Ed448PublicKey,
+)
+
+from ...utils import (
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
+)
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: not backend.ed448_supported(),
+ skip_message="Requires OpenSSL without Ed448 support",
+)
+def test_ed448_unsupported(backend):
+ with raises_unsupported_algorithm(
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
+ ):
+ Ed448PublicKey.from_public_bytes(b"0" * 57)
+
+ with raises_unsupported_algorithm(
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
+ ):
+ Ed448PrivateKey.from_private_bytes(b"0" * 57)
+
+ with raises_unsupported_algorithm(
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
+ ):
+ Ed448PrivateKey.generate()
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: backend.ed448_supported(),
+ skip_message="Requires OpenSSL with Ed448 support",
+)
+class TestEd448Signing(object):
+ @pytest.mark.parametrize(
+ "vector",
+ load_vectors_from_file(
+ os.path.join("asymmetric", "Ed448", "rfc8032.txt"),
+ load_nist_vectors,
+ ),
+ )
+ def test_sign_input(self, vector, backend):
+ if vector.get("context") is not None:
+ pytest.skip("ed448 contexts are not currently supported")
+
+ sk = binascii.unhexlify(vector["secret"])
+ pk = binascii.unhexlify(vector["public"])
+ message = binascii.unhexlify(vector["message"])
+ signature = binascii.unhexlify(vector["signature"])
+ private_key = Ed448PrivateKey.from_private_bytes(sk)
+ computed_sig = private_key.sign(message)
+ assert computed_sig == signature
+ public_key = private_key.public_key()
+ assert (
+ public_key.public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == pk
+ )
+ public_key.verify(signature, message)
+
+ def test_invalid_signature(self, backend):
+ key = Ed448PrivateKey.generate()
+ signature = key.sign(b"test data")
+ with pytest.raises(InvalidSignature):
+ key.public_key().verify(signature, b"wrong data")
+
+ with pytest.raises(InvalidSignature):
+ key.public_key().verify(b"0" * 64, b"test data")
+
+ def test_generate(self, backend):
+ key = Ed448PrivateKey.generate()
+ assert key
+ assert key.public_key()
+
+ @pytest.mark.parametrize(
+ "vector",
+ load_vectors_from_file(
+ os.path.join("asymmetric", "Ed448", "rfc8032.txt"),
+ load_nist_vectors,
+ ),
+ )
+ def test_pub_priv_bytes_raw(self, vector, backend):
+ sk = binascii.unhexlify(vector["secret"])
+ pk = binascii.unhexlify(vector["public"])
+ private_key = Ed448PrivateKey.from_private_bytes(sk)
+ assert (
+ private_key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+ == sk
+ )
+ assert (
+ private_key.public_key().public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == pk
+ )
+ public_key = Ed448PublicKey.from_public_bytes(pk)
+ assert (
+ public_key.public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == pk
+ )
+
+ @pytest.mark.parametrize(
+ ("encoding", "fmt", "encryption", "passwd", "load_func"),
+ [
+ (
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.BestAvailableEncryption(b"password"),
+ b"password",
+ serialization.load_pem_private_key,
+ ),
+ (
+ serialization.Encoding.DER,
+ serialization.PrivateFormat.PKCS8,
+ serialization.BestAvailableEncryption(b"password"),
+ b"password",
+ serialization.load_der_private_key,
+ ),
+ (
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ None,
+ serialization.load_pem_private_key,
+ ),
+ (
+ serialization.Encoding.DER,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ None,
+ serialization.load_der_private_key,
+ ),
+ ],
+ )
+ def test_round_trip_private_serialization(
+ self, encoding, fmt, encryption, passwd, load_func, backend
+ ):
+ key = Ed448PrivateKey.generate()
+ serialized = key.private_bytes(encoding, fmt, encryption)
+ loaded_key = load_func(serialized, passwd, backend)
+ assert isinstance(loaded_key, Ed448PrivateKey)
+
+ def test_invalid_type_public_bytes(self, backend):
+ with pytest.raises(TypeError):
+ Ed448PublicKey.from_public_bytes(object())
+
+ def test_invalid_type_private_bytes(self, backend):
+ with pytest.raises(TypeError):
+ Ed448PrivateKey.from_private_bytes(object())
+
+ def test_invalid_length_from_public_bytes(self, backend):
+ with pytest.raises(ValueError):
+ Ed448PublicKey.from_public_bytes(b"a" * 56)
+ with pytest.raises(ValueError):
+ Ed448PublicKey.from_public_bytes(b"a" * 58)
+
+ def test_invalid_length_from_private_bytes(self, backend):
+ with pytest.raises(ValueError):
+ Ed448PrivateKey.from_private_bytes(b"a" * 56)
+ with pytest.raises(ValueError):
+ Ed448PrivateKey.from_private_bytes(b"a" * 58)
+
+ def test_invalid_private_bytes(self, backend):
+ key = Ed448PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ None,
+ )
+
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.PKCS8,
+ None,
+ )
+
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+
+ def test_invalid_public_bytes(self, backend):
+ key = Ed448PrivateKey.generate().public_key()
+ with pytest.raises(ValueError):
+ key.public_bytes(
+ serialization.Encoding.Raw,
+ serialization.PublicFormat.SubjectPublicKeyInfo,
+ )
+
+ with pytest.raises(ValueError):
+ key.public_bytes(
+ serialization.Encoding.PEM, serialization.PublicFormat.PKCS1
+ )
+
+ with pytest.raises(ValueError):
+ key.public_bytes(
+ serialization.Encoding.PEM, serialization.PublicFormat.Raw
+ )
+
+ def test_buffer_protocol(self, backend):
+ private_bytes = os.urandom(57)
+ key = Ed448PrivateKey.from_private_bytes(bytearray(private_bytes))
+ assert (
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+ == private_bytes
+ )
+
+ def test_malleability(self, backend):
+ # This is a signature where r > the group order. It should be
+ # rejected to prevent signature malleability issues. This test can
+ # be removed when wycheproof grows ed448 vectors
+ public_bytes = binascii.unhexlify(
+ "fedb02a658d74990244d9d10cf338e977565cbbda6b24c716829ed6ee1e4f28cf"
+ "2620c052db8d878f6243bffc22242816c1aaa67d2f3603600"
+ )
+ signature = binascii.unhexlify(
+ "0cc16ba24d69277f927c1554b0f08a2a711bbdd20b058ccc660d00ca13542a3ce"
+ "f9e5c44c54ab23a2eb14f947e167b990b080863e28b399380f30db6e54d5d1406"
+ "d23378ffde11b1fb81b2b438a3b8e8aa7f7f4e1befcc905023fab5a5465053844"
+ "f04cf0c1b51d84760f869588687f57500"
+ )
+ key = Ed448PublicKey.from_public_bytes(public_bytes)
+ with pytest.raises(InvalidSignature):
+ key.verify(signature, b"8")
diff --git a/tests/hazmat/primitives/test_hash_vectors.py b/tests/hazmat/primitives/test_hash_vectors.py
index 5225a00..9301b62 100644
--- a/tests/hazmat/primitives/test_hash_vectors.py
+++ b/tests/hazmat/primitives/test_hash_vectors.py
@@ -22,13 +22,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA1(object):
- test_SHA1 = generate_hash_test(
+ test_sha1 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA1"),
- [
- "SHA1LongMsg.rsp",
- "SHA1ShortMsg.rsp",
- ],
+ ["SHA1LongMsg.rsp", "SHA1ShortMsg.rsp"],
hashes.SHA1(),
)
@@ -39,13 +36,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA224(object):
- test_SHA224 = generate_hash_test(
+ test_sha224 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
- [
- "SHA224LongMsg.rsp",
- "SHA224ShortMsg.rsp",
- ],
+ ["SHA224LongMsg.rsp", "SHA224ShortMsg.rsp"],
hashes.SHA224(),
)
@@ -56,13 +50,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA256(object):
- test_SHA256 = generate_hash_test(
+ test_sha256 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
- [
- "SHA256LongMsg.rsp",
- "SHA256ShortMsg.rsp",
- ],
+ ["SHA256LongMsg.rsp", "SHA256ShortMsg.rsp"],
hashes.SHA256(),
)
@@ -73,13 +64,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA384(object):
- test_SHA384 = generate_hash_test(
+ test_sha384 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
- [
- "SHA384LongMsg.rsp",
- "SHA384ShortMsg.rsp",
- ],
+ ["SHA384LongMsg.rsp", "SHA384ShortMsg.rsp"],
hashes.SHA384(),
)
@@ -90,13 +78,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA512(object):
- test_SHA512 = generate_hash_test(
+ test_sha512 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
- [
- "SHA512LongMsg.rsp",
- "SHA512ShortMsg.rsp",
- ],
+ ["SHA512LongMsg.rsp", "SHA512ShortMsg.rsp"],
hashes.SHA512(),
)
@@ -107,13 +92,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA512224(object):
- test_SHA512_224 = generate_hash_test(
+ test_sha512_224 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
- [
- "SHA512_224LongMsg.rsp",
- "SHA512_224ShortMsg.rsp",
- ],
+ ["SHA512_224LongMsg.rsp", "SHA512_224ShortMsg.rsp"],
hashes.SHA512_224(),
)
@@ -124,13 +106,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA512256(object):
- test_SHA512_256 = generate_hash_test(
+ test_sha512_256 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
- [
- "SHA512_256LongMsg.rsp",
- "SHA512_256ShortMsg.rsp",
- ],
+ ["SHA512_256LongMsg.rsp", "SHA512_256ShortMsg.rsp"],
hashes.SHA512_256(),
)
@@ -144,16 +123,15 @@
test_md5 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "MD5"),
- [
- "rfc-1321.txt",
- ],
+ ["rfc-1321.txt"],
hashes.MD5(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
- hashes.BLAKE2b(digest_size=64)),
+ hashes.BLAKE2b(digest_size=64)
+ ),
skip_message="Does not support BLAKE2b",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
@@ -161,16 +139,15 @@
test_b2b = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "blake2"),
- [
- "blake2b.txt",
- ],
+ ["blake2b.txt"],
hashes.BLAKE2b(digest_size=64),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
- hashes.BLAKE2s(digest_size=32)),
+ hashes.BLAKE2s(digest_size=32)
+ ),
skip_message="Does not support BLAKE2s",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
@@ -178,9 +155,7 @@
test_b2s = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "blake2"),
- [
- "blake2s.txt",
- ],
+ ["blake2s.txt"],
hashes.BLAKE2s(digest_size=32),
)
@@ -191,13 +166,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA3224(object):
- test_SHA3_224 = generate_hash_test(
+ test_sha3_224 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA3"),
- [
- "SHA3_224LongMsg.rsp",
- "SHA3_224ShortMsg.rsp",
- ],
+ ["SHA3_224LongMsg.rsp", "SHA3_224ShortMsg.rsp"],
hashes.SHA3_224(),
)
@@ -208,13 +180,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA3256(object):
- test_SHA3_256 = generate_hash_test(
+ test_sha3_256 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA3"),
- [
- "SHA3_256LongMsg.rsp",
- "SHA3_256ShortMsg.rsp",
- ],
+ ["SHA3_256LongMsg.rsp", "SHA3_256ShortMsg.rsp"],
hashes.SHA3_256(),
)
@@ -225,13 +194,10 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA3384(object):
- test_SHA3_384 = generate_hash_test(
+ test_sha3_384 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA3"),
- [
- "SHA3_384LongMsg.rsp",
- "SHA3_384ShortMsg.rsp",
- ],
+ ["SHA3_384LongMsg.rsp", "SHA3_384ShortMsg.rsp"],
hashes.SHA3_384(),
)
@@ -242,20 +208,18 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA3512(object):
- test_SHA3_512 = generate_hash_test(
+ test_sha3_512 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA3"),
- [
- "SHA3_512LongMsg.rsp",
- "SHA3_512ShortMsg.rsp",
- ],
+ ["SHA3_512LongMsg.rsp", "SHA3_512ShortMsg.rsp"],
hashes.SHA3_512(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
- hashes.SHAKE128(digest_size=16)),
+ hashes.SHAKE128(digest_size=16)
+ ),
skip_message="Does not support SHAKE128",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
@@ -263,10 +227,7 @@
test_shake128 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHAKE"),
- [
- "SHAKE128LongMsg.rsp",
- "SHAKE128ShortMsg.rsp",
- ],
+ ["SHAKE128LongMsg.rsp", "SHAKE128ShortMsg.rsp"],
hashes.SHAKE128(digest_size=16),
)
@@ -274,24 +235,23 @@
"vector",
_load_all_params(
os.path.join("hashes", "SHAKE"),
- [
- "SHAKE128VariableOut.rsp",
- ],
+ ["SHAKE128VariableOut.rsp"],
load_nist_vectors,
- )
+ ),
)
def test_shake128_variable(self, vector, backend):
- output_length = int(vector['outputlen']) // 8
- msg = binascii.unhexlify(vector['msg'])
+ output_length = int(vector["outputlen"]) // 8
+ msg = binascii.unhexlify(vector["msg"])
shake = hashes.SHAKE128(digest_size=output_length)
m = hashes.Hash(shake, backend=backend)
m.update(msg)
- assert m.finalize() == binascii.unhexlify(vector['output'])
+ assert m.finalize() == binascii.unhexlify(vector["output"])
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
- hashes.SHAKE256(digest_size=32)),
+ hashes.SHAKE256(digest_size=32)
+ ),
skip_message="Does not support SHAKE256",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
@@ -299,10 +259,7 @@
test_shake256 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHAKE"),
- [
- "SHAKE256LongMsg.rsp",
- "SHAKE256ShortMsg.rsp",
- ],
+ ["SHAKE256LongMsg.rsp", "SHAKE256ShortMsg.rsp"],
hashes.SHAKE256(digest_size=32),
)
@@ -310,16 +267,14 @@
"vector",
_load_all_params(
os.path.join("hashes", "SHAKE"),
- [
- "SHAKE256VariableOut.rsp",
- ],
+ ["SHAKE256VariableOut.rsp"],
load_nist_vectors,
- )
+ ),
)
def test_shake256_variable(self, vector, backend):
- output_length = int(vector['outputlen']) // 8
- msg = binascii.unhexlify(vector['msg'])
+ output_length = int(vector["outputlen"]) // 8
+ msg = binascii.unhexlify(vector["msg"])
shake = hashes.SHAKE256(digest_size=output_length)
m = hashes.Hash(shake, backend=backend)
m.update(msg)
- assert m.finalize() == binascii.unhexlify(vector['output'])
+ assert m.finalize() == binascii.unhexlify(vector["output"])
diff --git a/tests/hazmat/primitives/test_hashes.py b/tests/hazmat/primitives/test_hashes.py
index b10fadc..eadd0fe 100644
--- a/tests/hazmat/primitives/test_hashes.py
+++ b/tests/hazmat/primitives/test_hashes.py
@@ -52,7 +52,7 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA1(object):
- test_SHA1 = generate_base_hash_test(
+ test_sha1 = generate_base_hash_test(
hashes.SHA1(),
digest_size=20,
)
@@ -64,7 +64,7 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA224(object):
- test_SHA224 = generate_base_hash_test(
+ test_sha224 = generate_base_hash_test(
hashes.SHA224(),
digest_size=28,
)
@@ -76,7 +76,7 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA256(object):
- test_SHA256 = generate_base_hash_test(
+ test_sha256 = generate_base_hash_test(
hashes.SHA256(),
digest_size=32,
)
@@ -88,7 +88,7 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA384(object):
- test_SHA384 = generate_base_hash_test(
+ test_sha384 = generate_base_hash_test(
hashes.SHA384(),
digest_size=48,
)
@@ -100,7 +100,7 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA512(object):
- test_SHA512 = generate_base_hash_test(
+ test_sha512 = generate_base_hash_test(
hashes.SHA512(),
digest_size=64,
)
@@ -112,7 +112,7 @@
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestMD5(object):
- test_MD5 = generate_base_hash_test(
+ test_md5 = generate_base_hash_test(
hashes.MD5(),
digest_size=16,
)
@@ -120,12 +120,13 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
- hashes.BLAKE2b(digest_size=64)),
+ hashes.BLAKE2b(digest_size=64)
+ ),
skip_message="Does not support BLAKE2b",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestBLAKE2b(object):
- test_BLAKE2b = generate_base_hash_test(
+ test_blake2b = generate_base_hash_test(
hashes.BLAKE2b(digest_size=64),
digest_size=64,
)
@@ -143,12 +144,13 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
- hashes.BLAKE2s(digest_size=32)),
+ hashes.BLAKE2s(digest_size=32)
+ ),
skip_message="Does not support BLAKE2s",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestBLAKE2s(object):
- test_BLAKE2s = generate_base_hash_test(
+ test_blake2s = generate_base_hash_test(
hashes.BLAKE2s(digest_size=32),
digest_size=32,
)
@@ -182,18 +184,12 @@
class TestSHAKE(object):
- @pytest.mark.parametrize(
- "xof",
- [hashes.SHAKE128, hashes.SHAKE256]
- )
+ @pytest.mark.parametrize("xof", [hashes.SHAKE128, hashes.SHAKE256])
def test_invalid_digest_type(self, xof):
with pytest.raises(TypeError):
xof(digest_size=object())
- @pytest.mark.parametrize(
- "xof",
- [hashes.SHAKE128, hashes.SHAKE256]
- )
+ @pytest.mark.parametrize("xof", [hashes.SHAKE128, hashes.SHAKE256])
def test_invalid_digest_size(self, xof):
with pytest.raises(ValueError):
xof(digest_size=-5)
diff --git a/tests/hazmat/primitives/test_hkdf.py b/tests/hazmat/primitives/test_hkdf.py
index 195bfb3..1d7de6c 100644
--- a/tests/hazmat/primitives/test_hkdf.py
+++ b/tests/hazmat/primitives/test_hkdf.py
@@ -9,15 +9,15 @@
import pytest
-from cryptography.exceptions import (
- AlreadyFinalized, InvalidKey, _Reasons
-)
+from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons
from cryptography.hazmat.backends.interfaces import HMACBackend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF, HKDFExpand
from ...utils import (
- load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
@@ -32,127 +32,67 @@
big_length,
salt=None,
info=None,
- backend=backend
+ backend=backend,
)
def test_already_finalized(self, backend):
- hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
- )
+ hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend)
hkdf.derive(b"\x01" * 16)
with pytest.raises(AlreadyFinalized):
hkdf.derive(b"\x02" * 16)
- hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
- )
+ hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend)
hkdf.verify(b"\x01" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")
with pytest.raises(AlreadyFinalized):
hkdf.verify(b"\x02" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")
- hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
- )
+ hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend)
def test_verify(self, backend):
- hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
- )
+ hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend)
hkdf.verify(b"\x01" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")
def test_verify_invalid(self, backend):
- hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
- )
+ hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend)
with pytest.raises(InvalidKey):
hkdf.verify(b"\x02" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")
def test_unicode_typeerror(self, backend):
with pytest.raises(TypeError):
- HKDF(
- hashes.SHA256(),
- 16,
- salt=u"foo",
- info=None,
- backend=backend
- )
+ HKDF(hashes.SHA256(), 16, salt=u"foo", info=None, backend=backend)
with pytest.raises(TypeError):
- HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=u"foo",
- backend=backend
- )
+ HKDF(hashes.SHA256(), 16, salt=None, info=u"foo", backend=backend)
with pytest.raises(TypeError):
hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
+ hashes.SHA256(), 16, salt=None, info=None, backend=backend
)
hkdf.derive(u"foo")
with pytest.raises(TypeError):
hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
+ hashes.SHA256(), 16, salt=None, info=None, backend=backend
)
hkdf.verify(u"foo", b"bar")
with pytest.raises(TypeError):
hkdf = HKDF(
- hashes.SHA256(),
- 16,
- salt=None,
- info=None,
- backend=backend
+ hashes.SHA256(), 16, salt=None, info=None, backend=backend
)
hkdf.verify(b"foo", u"bar")
def test_derive_short_output(self, backend):
- hkdf = HKDF(
- hashes.SHA256(),
- 4,
- salt=None,
- info=None,
- backend=backend
- )
+ hkdf = HKDF(hashes.SHA256(), 4, salt=None, info=None, backend=backend)
assert hkdf.derive(b"\x01" * 16) == b"gJ\xfb{"
@@ -165,7 +105,7 @@
int(vector["l"]),
salt=vector["salt"],
info=vector["info"],
- backend=backend
+ backend=backend,
)
ikm = binascii.unhexlify(vector["ikm"])
@@ -180,7 +120,7 @@
int(vector["l"]),
salt=vector["salt"],
info=vector["info"],
- backend=backend
+ backend=backend,
)
ikm = bytearray(binascii.unhexlify(vector["ikm"]))
@@ -194,8 +134,10 @@
b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"
)
- okm = (b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c"
- b"5bf34007208d5b887185865")
+ okm = (
+ b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c"
+ b"5bf34007208d5b887185865"
+ )
info = binascii.unhexlify(b"f0f1f2f3f4f5f6f7f8f9")
hkdf = HKDFExpand(hashes.SHA256(), 42, info, backend)
@@ -203,12 +145,17 @@
assert binascii.hexlify(hkdf.derive(prk)) == okm
def test_buffer_protocol(self, backend):
- prk = bytearray(binascii.unhexlify(
- b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"
- ))
+ prk = bytearray(
+ binascii.unhexlify(
+ b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2"
+ b"b3e5"
+ )
+ )
- okm = (b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c"
- b"5bf34007208d5b887185865")
+ okm = (
+ b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c"
+ b"5bf34007208d5b887185865"
+ )
info = binascii.unhexlify(b"f0f1f2f3f4f5f6f7f8f9")
hkdf = HKDFExpand(hashes.SHA256(), 42, info, backend)
@@ -220,8 +167,10 @@
b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"
)
- okm = (b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c"
- b"5bf34007208d5b887185865")
+ okm = (
+ b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c"
+ b"5bf34007208d5b887185865"
+ )
info = binascii.unhexlify(b"f0f1f2f3f4f5f6f7f8f9")
hkdf = HKDFExpand(hashes.SHA256(), 42, info, backend)
diff --git a/tests/hazmat/primitives/test_hkdf_vectors.py b/tests/hazmat/primitives/test_hkdf_vectors.py
index 74bf929..97385e2 100644
--- a/tests/hazmat/primitives/test_hkdf_vectors.py
+++ b/tests/hazmat/primitives/test_hkdf_vectors.py
@@ -17,27 +17,27 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA1()),
- skip_message="Does not support SHA1."
+ skip_message="Does not support SHA1.",
)
@pytest.mark.requires_backend_interface(interface=HMACBackend)
class TestHKDFSHA1(object):
- test_HKDFSHA1 = generate_hkdf_test(
+ test_hkdfsha1 = generate_hkdf_test(
load_nist_vectors,
os.path.join("KDF"),
["rfc-5869-HKDF-SHA1.txt"],
- hashes.SHA1()
+ hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA256()),
- skip_message="Does not support SHA256."
+ skip_message="Does not support SHA256.",
)
@pytest.mark.requires_backend_interface(interface=HMACBackend)
class TestHKDFSHA256(object):
- test_HKDFSHA1 = generate_hkdf_test(
+ test_hkdfsha256 = generate_hkdf_test(
load_nist_vectors,
os.path.join("KDF"),
["rfc-5869-HKDF-SHA256.txt"],
- hashes.SHA256()
+ hashes.SHA256(),
)
diff --git a/tests/hazmat/primitives/test_hmac.py b/tests/hazmat/primitives/test_hmac.py
index 0e2fe68..7ea931a 100644
--- a/tests/hazmat/primitives/test_hmac.py
+++ b/tests/hazmat/primitives/test_hmac.py
@@ -9,7 +9,9 @@
import pytest
from cryptography.exceptions import (
- AlreadyFinalized, InvalidSignature, _Reasons
+ AlreadyFinalized,
+ InvalidSignature,
+ _Reasons,
)
from cryptography.hazmat.backends.interfaces import HMACBackend
from cryptography.hazmat.primitives import hashes, hmac
@@ -55,27 +57,27 @@
h.finalize()
def test_verify(self, backend):
- h = hmac.HMAC(b'', hashes.SHA1(), backend=backend)
+ h = hmac.HMAC(b"", hashes.SHA1(), backend=backend)
digest = h.finalize()
- h = hmac.HMAC(b'', hashes.SHA1(), backend=backend)
+ h = hmac.HMAC(b"", hashes.SHA1(), backend=backend)
h.verify(digest)
with pytest.raises(AlreadyFinalized):
- h.verify(b'')
+ h.verify(b"")
def test_invalid_verify(self, backend):
- h = hmac.HMAC(b'', hashes.SHA1(), backend=backend)
+ h = hmac.HMAC(b"", hashes.SHA1(), backend=backend)
with pytest.raises(InvalidSignature):
- h.verify(b'')
+ h.verify(b"")
with pytest.raises(AlreadyFinalized):
- h.verify(b'')
+ h.verify(b"")
def test_verify_reject_unicode(self, backend):
- h = hmac.HMAC(b'', hashes.SHA1(), backend=backend)
+ h = hmac.HMAC(b"", hashes.SHA1(), backend=backend)
with pytest.raises(TypeError):
- h.verify(u'')
+ h.verify(u"")
def test_unsupported_hash(self, backend):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
diff --git a/tests/hazmat/primitives/test_hmac_vectors.py b/tests/hazmat/primitives/test_hmac_vectors.py
index 6ff71fe..b39df1a 100644
--- a/tests/hazmat/primitives/test_hmac_vectors.py
+++ b/tests/hazmat/primitives/test_hmac_vectors.py
@@ -24,9 +24,7 @@
test_hmac_md5 = generate_hmac_test(
load_hash_vectors,
"HMAC",
- [
- "rfc-2202-md5.txt",
- ],
+ ["rfc-2202-md5.txt"],
hashes.MD5(),
)
@@ -40,9 +38,7 @@
test_hmac_sha1 = generate_hmac_test(
load_hash_vectors,
"HMAC",
- [
- "rfc-2202-sha1.txt",
- ],
+ ["rfc-2202-sha1.txt"],
hashes.SHA1(),
)
@@ -56,9 +52,7 @@
test_hmac_sha224 = generate_hmac_test(
load_hash_vectors,
"HMAC",
- [
- "rfc-4231-sha224.txt",
- ],
+ ["rfc-4231-sha224.txt"],
hashes.SHA224(),
)
@@ -72,9 +66,7 @@
test_hmac_sha256 = generate_hmac_test(
load_hash_vectors,
"HMAC",
- [
- "rfc-4231-sha256.txt",
- ],
+ ["rfc-4231-sha256.txt"],
hashes.SHA256(),
)
@@ -88,9 +80,7 @@
test_hmac_sha384 = generate_hmac_test(
load_hash_vectors,
"HMAC",
- [
- "rfc-4231-sha384.txt",
- ],
+ ["rfc-4231-sha384.txt"],
hashes.SHA384(),
)
@@ -104,17 +94,15 @@
test_hmac_sha512 = generate_hmac_test(
load_hash_vectors,
"HMAC",
- [
- "rfc-4231-sha512.txt",
- ],
+ ["rfc-4231-sha512.txt"],
hashes.SHA512(),
)
@pytest.mark.supported(
- only_if=lambda backend: backend.hmac_supported(hashes.BLAKE2b(
- digest_size=64
- )),
+ only_if=lambda backend: backend.hmac_supported(
+ hashes.BLAKE2b(digest_size=64)
+ ),
skip_message="Does not support BLAKE2",
)
@pytest.mark.requires_backend_interface(interface=HMACBackend)
diff --git a/tests/hazmat/primitives/test_idea.py b/tests/hazmat/primitives/test_idea.py
index 75116dc..1f766de 100644
--- a/tests/hazmat/primitives/test_idea.py
+++ b/tests/hazmat/primitives/test_idea.py
@@ -24,7 +24,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeECB(object):
- test_ECB = generate_encrypt_test(
+ test_ecb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "IDEA"),
["idea-ecb.txt"],
@@ -41,12 +41,12 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeCBC(object):
- test_CBC = generate_encrypt_test(
+ test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "IDEA"),
["idea-cbc.txt"],
lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
)
@@ -58,12 +58,12 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeOFB(object):
- test_OFB = generate_encrypt_test(
+ test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "IDEA"),
["idea-ofb.txt"],
lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)),
)
@@ -75,10 +75,10 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeCFB(object):
- test_CFB = generate_encrypt_test(
+ test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "IDEA"),
["idea-cfb.txt"],
lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
)
diff --git a/tests/hazmat/primitives/test_kbkdf.py b/tests/hazmat/primitives/test_kbkdf.py
index a16f176..5ff5d74 100644
--- a/tests/hazmat/primitives/test_kbkdf.py
+++ b/tests/hazmat/primitives/test_kbkdf.py
@@ -6,13 +6,13 @@
import pytest
-from cryptography.exceptions import (
- AlreadyFinalized, InvalidKey, _Reasons
-)
+from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons
from cryptography.hazmat.backends.interfaces import HMACBackend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.kbkdf import (
- CounterLocation, KBKDFHMAC, Mode
+ CounterLocation,
+ KBKDFHMAC,
+ Mode,
)
from ...doubles import DummyHashAlgorithm
@@ -22,137 +22,316 @@
@pytest.mark.requires_backend_interface(interface=HMACBackend)
class TestKBKDFHMAC(object):
def test_invalid_key(self, backend):
- kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ kdf = KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
key = kdf.derive(b"material")
- kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ kdf = KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
with pytest.raises(InvalidKey):
kdf.verify(b"material2", key)
def test_already_finalized(self, backend):
- kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ kdf = KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
- kdf.derive(b'material')
+ kdf.derive(b"material")
with pytest.raises(AlreadyFinalized):
- kdf.derive(b'material2')
+ kdf.derive(b"material2")
- kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ kdf = KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
- key = kdf.derive(b'material')
+ key = kdf.derive(b"material")
with pytest.raises(AlreadyFinalized):
- kdf.verify(b'material', key)
+ kdf.verify(b"material", key)
- kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
- kdf.verify(b'material', key)
+ kdf = KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
+ kdf.verify(b"material", key)
with pytest.raises(AlreadyFinalized):
kdf.verify(b"material", key)
def test_key_length(self, backend):
- kdf = KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 85899345920, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ kdf = KBKDFHMAC(
+ hashes.SHA1(),
+ Mode.CounterMode,
+ 85899345920,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
with pytest.raises(ValueError):
- kdf.derive(b'material')
+ kdf.derive(b"material")
def test_rlen(self, backend):
with pytest.raises(ValueError):
- KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 5, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 5,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_r_type(self, backend):
with pytest.raises(TypeError):
- KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 32, b'r', 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ KBKDFHMAC(
+ hashes.SHA1(),
+ Mode.CounterMode,
+ 32,
+ b"r",
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_l_type(self, backend):
with pytest.raises(TypeError):
- KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 32, 4, b'l',
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ KBKDFHMAC(
+ hashes.SHA1(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ b"l",
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_l(self, backend):
with pytest.raises(ValueError):
- KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 32, 4, None,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ KBKDFHMAC(
+ hashes.SHA1(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ None,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_unsupported_mode(self, backend):
with pytest.raises(TypeError):
- KBKDFHMAC(hashes.SHA256(), None, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ KBKDFHMAC(
+ hashes.SHA256(),
+ None,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_unsupported_location(self, backend):
with pytest.raises(TypeError):
- KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- None, b'label', b'context', None,
- backend=backend)
+ KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ None,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_unsupported_parameters(self, backend):
with pytest.raises(ValueError):
- KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- b'fixed', backend=backend)
+ KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ b"fixed",
+ backend=backend,
+ )
def test_unsupported_hash(self, backend):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
- KBKDFHMAC(object(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ KBKDFHMAC(
+ object(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_unsupported_algorithm(self, backend):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
- KBKDFHMAC(DummyHashAlgorithm(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ KBKDFHMAC(
+ DummyHashAlgorithm(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
def test_invalid_backend(self, backend):
with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE):
- KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=object())
+ KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=object(),
+ )
def test_unicode_error_label(self, backend):
with pytest.raises(TypeError):
- KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, u'label', b'context',
- backend=backend)
+ KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ u"label",
+ b"context",
+ backend=backend,
+ )
def test_unicode_error_context(self, backend):
with pytest.raises(TypeError):
- KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label', u'context',
- None, backend=backend)
+ KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ u"context",
+ None,
+ backend=backend,
+ )
def test_unicode_error_key_material(self, backend):
with pytest.raises(TypeError):
- kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4,
- CounterLocation.BeforeFixed, b'label',
- b'context', None, backend=backend)
- kdf.derive(u'material')
+ kdf = KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 32,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
+ kdf.derive(u"material")
def test_buffer_protocol(self, backend):
- kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 10, 4, 4,
- CounterLocation.BeforeFixed, b'label', b'context',
- None, backend=backend)
+ kdf = KBKDFHMAC(
+ hashes.SHA256(),
+ Mode.CounterMode,
+ 10,
+ 4,
+ 4,
+ CounterLocation.BeforeFixed,
+ b"label",
+ b"context",
+ None,
+ backend=backend,
+ )
key = kdf.derive(bytearray(b"material"))
- assert key == b'\xb7\x01\x05\x98\xf5\x1a\x12L\xc7.'
+ assert key == b"\xb7\x01\x05\x98\xf5\x1a\x12L\xc7."
diff --git a/tests/hazmat/primitives/test_kbkdf_vectors.py b/tests/hazmat/primitives/test_kbkdf_vectors.py
index c8263e2..462e04e 100644
--- a/tests/hazmat/primitives/test_kbkdf_vectors.py
+++ b/tests/hazmat/primitives/test_kbkdf_vectors.py
@@ -16,8 +16,8 @@
@pytest.mark.requires_backend_interface(interface=HMACBackend)
class TestCounterKDFCounterMode(object):
- test_HKDFSHA1 = generate_kbkdf_counter_mode_test(
+ test_kbkdfctr = generate_kbkdf_counter_mode_test(
load_nist_kbkdf_vectors,
os.path.join("KDF"),
- ["nist-800-108-KBKDF-CTR.txt"]
+ ["nist-800-108-KBKDF-CTR.txt"],
)
diff --git a/tests/hazmat/primitives/test_keywrap.py b/tests/hazmat/primitives/test_keywrap.py
index c74b144..9b91ccf 100644
--- a/tests/hazmat/primitives/test_keywrap.py
+++ b/tests/hazmat/primitives/test_keywrap.py
@@ -24,15 +24,15 @@
_load_all_params(
os.path.join("keywrap", "kwtestvectors"),
["KW_AE_128.txt", "KW_AE_192.txt", "KW_AE_256.txt"],
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
algorithms.AES(b"\x00" * 16), modes.ECB()
),
skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
- " is unsupported",
+ " is unsupported",
)
def test_wrap(self, backend, params):
wrapping_key = binascii.unhexlify(params["k"])
@@ -45,15 +45,15 @@
_load_all_params(
os.path.join("keywrap", "kwtestvectors"),
["KW_AD_128.txt", "KW_AD_192.txt", "KW_AD_256.txt"],
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
algorithms.AES(b"\x00" * 16), modes.ECB()
),
skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
- " is unsupported",
+ " is unsupported",
)
def test_unwrap(self, backend, params):
wrapping_key = binascii.unhexlify(params["k"])
@@ -72,7 +72,7 @@
algorithms.AES(b"\x00" * 16), modes.ECB()
),
skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
- " is unsupported",
+ " is unsupported",
)
def test_wrap_invalid_key_length(self, backend):
# The wrapping key must be of length [16, 24, 32]
@@ -84,7 +84,7 @@
algorithms.AES(b"\x00" * 16), modes.ECB()
),
skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
- " is unsupported",
+ " is unsupported",
)
def test_unwrap_invalid_key_length(self, backend):
with pytest.raises(ValueError):
@@ -95,7 +95,7 @@
algorithms.AES(b"\x00" * 16), modes.ECB()
),
skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
- " is unsupported",
+ " is unsupported",
)
def test_wrap_invalid_key_to_wrap_length(self, backend):
# Keys to wrap must be at least 16 bytes long
@@ -121,7 +121,7 @@
algorithms.AES(b"\x00" * 16), modes.ECB()
),
skip_message="Does not support AES key wrap (RFC 5649) because AES-ECB"
- " is unsupported",
+ " is unsupported",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestAESKeyWrapWithPadding(object):
@@ -130,8 +130,8 @@
_load_all_params(
os.path.join("keywrap", "kwtestvectors"),
["KWP_AE_128.txt", "KWP_AE_192.txt", "KWP_AE_256.txt"],
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_wrap(self, backend, params):
wrapping_key = binascii.unhexlify(params["k"])
@@ -143,7 +143,7 @@
@pytest.mark.parametrize(
"params",
- _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors)
+ _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors),
)
def test_wrap_additional_vectors(self, backend, params):
wrapping_key = binascii.unhexlify(params["key"])
@@ -158,8 +158,8 @@
_load_all_params(
os.path.join("keywrap", "kwtestvectors"),
["KWP_AD_128.txt", "KWP_AD_192.txt", "KWP_AD_256.txt"],
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_unwrap(self, backend, params):
wrapping_key = binascii.unhexlify(params["k"])
@@ -177,7 +177,7 @@
@pytest.mark.parametrize(
"params",
- _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors)
+ _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors),
)
def test_unwrap_additional_vectors(self, backend, params):
wrapping_key = binascii.unhexlify(params["key"])
@@ -190,18 +190,18 @@
def test_unwrap_invalid_wrapped_key_length(self, backend):
# Keys to unwrap must be at least 16 bytes
with pytest.raises(
- keywrap.InvalidUnwrap, match='Must be at least 16 bytes'
+ keywrap.InvalidUnwrap, match="Must be at least 16 bytes"
):
keywrap.aes_key_unwrap_with_padding(
b"sixteen_byte_key", b"\x00" * 15, backend
)
def test_wrap_invalid_key_length(self, backend):
- with pytest.raises(ValueError, match='must be a valid AES key length'):
+ with pytest.raises(ValueError, match="must be a valid AES key length"):
keywrap.aes_key_wrap_with_padding(b"badkey", b"\x00", backend)
def test_unwrap_invalid_key_length(self, backend):
- with pytest.raises(ValueError, match='must be a valid AES key length'):
+ with pytest.raises(ValueError, match="must be a valid AES key length"):
keywrap.aes_key_unwrap_with_padding(
b"badkey", b"\x00" * 16, backend
)
diff --git a/tests/hazmat/primitives/test_padding.py b/tests/hazmat/primitives/test_padding.py
index fb72a79..b15eb37 100644
--- a/tests/hazmat/primitives/test_padding.py
+++ b/tests/hazmat/primitives/test_padding.py
@@ -18,14 +18,17 @@
with pytest.raises(ValueError):
padding.PKCS7(size)
- @pytest.mark.parametrize(("size", "padded"), [
- (128, b"1111"),
- (128, b"1111111111111111"),
- (128, b"111111111111111\x06"),
- (128, b""),
- (128, b"\x06" * 6),
- (128, b"\x00" * 16),
- ])
+ @pytest.mark.parametrize(
+ ("size", "padded"),
+ [
+ (128, b"1111"),
+ (128, b"1111111111111111"),
+ (128, b"111111111111111\x06"),
+ (128, b""),
+ (128, b"\x06" * 6),
+ (128, b"\x00" * 16),
+ ],
+ )
def test_invalid_padding(self, size, padded):
unpadder = padding.PKCS7(size).unpadder()
with pytest.raises(ValueError):
@@ -40,46 +43,48 @@
with pytest.raises(TypeError):
unpadder.update(u"abc")
- @pytest.mark.parametrize(("size", "unpadded", "padded"), [
- (
- 128,
- b"1111111111",
- b"1111111111\x06\x06\x06\x06\x06\x06",
- ),
- (
- 128,
- b"111111111111111122222222222222",
- b"111111111111111122222222222222\x02\x02",
- ),
- (
- 128,
- b"1" * 16,
- b"1" * 16 + b"\x10" * 16,
- ),
- (
- 128,
- b"1" * 17,
- b"1" * 17 + b"\x0F" * 15,
- )
- ])
+ def test_zany_py2_bytes_subclass(self):
+ class mybytes(bytes): # noqa: N801
+ def __str__(self):
+ return "broken"
+
+ str(mybytes())
+ padder = padding.PKCS7(128).padder()
+ padder.update(mybytes(b"abc"))
+ unpadder = padding.PKCS7(128).unpadder()
+ unpadder.update(mybytes(padder.finalize()))
+ assert unpadder.finalize() == b"abc"
+
+ @pytest.mark.parametrize(
+ ("size", "unpadded", "padded"),
+ [
+ (128, b"1111111111", b"1111111111\x06\x06\x06\x06\x06\x06"),
+ (
+ 128,
+ b"111111111111111122222222222222",
+ b"111111111111111122222222222222\x02\x02",
+ ),
+ (128, b"1" * 16, b"1" * 16 + b"\x10" * 16),
+ (128, b"1" * 17, b"1" * 17 + b"\x0F" * 15),
+ ],
+ )
def test_pad(self, size, unpadded, padded):
padder = padding.PKCS7(size).padder()
result = padder.update(unpadded)
result += padder.finalize()
assert result == padded
- @pytest.mark.parametrize(("size", "unpadded", "padded"), [
- (
- 128,
- b"1111111111",
- b"1111111111\x06\x06\x06\x06\x06\x06",
- ),
- (
- 128,
- b"111111111111111122222222222222",
- b"111111111111111122222222222222\x02\x02",
- ),
- ])
+ @pytest.mark.parametrize(
+ ("size", "unpadded", "padded"),
+ [
+ (128, b"1111111111", b"1111111111\x06\x06\x06\x06\x06\x06"),
+ (
+ 128,
+ b"111111111111111122222222222222",
+ b"111111111111111122222222222222\x02\x02",
+ ),
+ ],
+ )
def test_unpad(self, size, unpadded, padded):
unpadder = padding.PKCS7(size).unpadder()
result = unpadder.update(padded)
@@ -116,6 +121,18 @@
assert data == b""
+ def test_bytearray(self):
+ padder = padding.PKCS7(128).padder()
+ unpadded = bytearray(b"t" * 38)
+ padded = (
+ padder.update(unpadded)
+ + padder.update(unpadded)
+ + padder.finalize()
+ )
+ unpadder = padding.PKCS7(128).unpadder()
+ final = unpadder.update(padded) + unpadder.finalize()
+ assert final == unpadded + unpadded
+
class TestANSIX923(object):
@pytest.mark.parametrize("size", [127, 4096, -2])
@@ -123,15 +140,18 @@
with pytest.raises(ValueError):
padding.ANSIX923(size)
- @pytest.mark.parametrize(("size", "padded"), [
- (128, b"1111"),
- (128, b"1111111111111111"),
- (128, b"111111111111111\x06"),
- (128, b"1111111111\x06\x06\x06\x06\x06\x06"),
- (128, b""),
- (128, b"\x06" * 6),
- (128, b"\x00" * 16),
- ])
+ @pytest.mark.parametrize(
+ ("size", "padded"),
+ [
+ (128, b"1111"),
+ (128, b"1111111111111111"),
+ (128, b"111111111111111\x06"),
+ (128, b"1111111111\x06\x06\x06\x06\x06\x06"),
+ (128, b""),
+ (128, b"\x06" * 6),
+ (128, b"\x00" * 16),
+ ],
+ )
def test_invalid_padding(self, size, padded):
unpadder = padding.ANSIX923(size).unpadder()
with pytest.raises(ValueError):
@@ -146,46 +166,48 @@
with pytest.raises(TypeError):
unpadder.update(u"abc")
- @pytest.mark.parametrize(("size", "unpadded", "padded"), [
- (
- 128,
- b"1111111111",
- b"1111111111\x00\x00\x00\x00\x00\x06",
- ),
- (
- 128,
- b"111111111111111122222222222222",
- b"111111111111111122222222222222\x00\x02",
- ),
- (
- 128,
- b"1" * 16,
- b"1" * 16 + b"\x00" * 15 + b"\x10",
- ),
- (
- 128,
- b"1" * 17,
- b"1" * 17 + b"\x00" * 14 + b"\x0F",
- )
- ])
+ def test_zany_py2_bytes_subclass(self):
+ class mybytes(bytes): # noqa: N801
+ def __str__(self):
+ return "broken"
+
+ str(mybytes())
+ padder = padding.ANSIX923(128).padder()
+ padder.update(mybytes(b"abc"))
+ unpadder = padding.ANSIX923(128).unpadder()
+ unpadder.update(mybytes(padder.finalize()))
+ assert unpadder.finalize() == b"abc"
+
+ @pytest.mark.parametrize(
+ ("size", "unpadded", "padded"),
+ [
+ (128, b"1111111111", b"1111111111\x00\x00\x00\x00\x00\x06"),
+ (
+ 128,
+ b"111111111111111122222222222222",
+ b"111111111111111122222222222222\x00\x02",
+ ),
+ (128, b"1" * 16, b"1" * 16 + b"\x00" * 15 + b"\x10"),
+ (128, b"1" * 17, b"1" * 17 + b"\x00" * 14 + b"\x0F"),
+ ],
+ )
def test_pad(self, size, unpadded, padded):
padder = padding.ANSIX923(size).padder()
result = padder.update(unpadded)
result += padder.finalize()
assert result == padded
- @pytest.mark.parametrize(("size", "unpadded", "padded"), [
- (
- 128,
- b"1111111111",
- b"1111111111\x00\x00\x00\x00\x00\x06",
- ),
- (
- 128,
- b"111111111111111122222222222222",
- b"111111111111111122222222222222\x00\x02",
- ),
- ])
+ @pytest.mark.parametrize(
+ ("size", "unpadded", "padded"),
+ [
+ (128, b"1111111111", b"1111111111\x00\x00\x00\x00\x00\x06"),
+ (
+ 128,
+ b"111111111111111122222222222222",
+ b"111111111111111122222222222222\x00\x02",
+ ),
+ ],
+ )
def test_unpad(self, size, unpadded, padded):
unpadder = padding.ANSIX923(size).unpadder()
result = unpadder.update(padded)
@@ -207,3 +229,15 @@
unpadder.update(b"")
with pytest.raises(AlreadyFinalized):
unpadder.finalize()
+
+ def test_bytearray(self):
+ padder = padding.ANSIX923(128).padder()
+ unpadded = bytearray(b"t" * 38)
+ padded = (
+ padder.update(unpadded)
+ + padder.update(unpadded)
+ + padder.finalize()
+ )
+ unpadder = padding.ANSIX923(128).unpadder()
+ final = unpadder.update(padded) + unpadder.finalize()
+ assert final == unpadded + unpadded
diff --git a/tests/hazmat/primitives/test_pbkdf2hmac.py b/tests/hazmat/primitives/test_pbkdf2hmac.py
index 0254b21..34fd25c 100644
--- a/tests/hazmat/primitives/test_pbkdf2hmac.py
+++ b/tests/hazmat/primitives/test_pbkdf2hmac.py
@@ -6,10 +6,7 @@
import pytest
-from cryptography.exceptions import (
- AlreadyFinalized, InvalidKey, _Reasons
-)
-from cryptography.hazmat.backends import default_backend
+from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
@@ -18,47 +15,45 @@
class TestPBKDF2HMAC(object):
- def test_already_finalized(self):
- kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend())
+ def test_already_finalized(self, backend):
+ kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
kdf.derive(b"password")
with pytest.raises(AlreadyFinalized):
kdf.derive(b"password2")
- kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend())
+ kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
key = kdf.derive(b"password")
with pytest.raises(AlreadyFinalized):
kdf.verify(b"password", key)
- kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend())
+ kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
kdf.verify(b"password", key)
with pytest.raises(AlreadyFinalized):
kdf.verify(b"password", key)
- def test_unsupported_algorithm(self):
+ def test_unsupported_algorithm(self, backend):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
- PBKDF2HMAC(
- DummyHashAlgorithm(), 20, b"salt", 10, default_backend()
- )
+ PBKDF2HMAC(DummyHashAlgorithm(), 20, b"salt", 10, backend)
- def test_invalid_key(self):
- kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend())
+ def test_invalid_key(self, backend):
+ kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
key = kdf.derive(b"password")
- kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend())
+ kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
with pytest.raises(InvalidKey):
kdf.verify(b"password2", key)
- def test_unicode_error_with_salt(self):
+ def test_unicode_error_with_salt(self, backend):
with pytest.raises(TypeError):
- PBKDF2HMAC(hashes.SHA1(), 20, u"salt", 10, default_backend())
+ PBKDF2HMAC(hashes.SHA1(), 20, u"salt", 10, backend)
- def test_unicode_error_with_key_material(self):
- kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend())
+ def test_unicode_error_with_key_material(self, backend):
+ kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
with pytest.raises(TypeError):
kdf.derive(u"unicode here")
def test_buffer_protocol(self, backend):
- kdf = PBKDF2HMAC(hashes.SHA1(), 10, b"salt", 10, default_backend())
+ kdf = PBKDF2HMAC(hashes.SHA1(), 10, b"salt", 10, backend)
data = bytearray(b"data")
assert kdf.derive(data) == b"\xe9n\xaa\x81\xbbt\xa4\xf6\x08\xce"
diff --git a/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py b/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py
index fe51f54..4b97b0d 100644
--- a/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py
+++ b/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py
@@ -22,8 +22,6 @@
test_pbkdf2_sha1 = generate_pbkdf2_test(
load_nist_vectors,
"KDF",
- [
- "rfc-6070-PBKDF2-SHA1.txt",
- ],
+ ["rfc-6070-PBKDF2-SHA1.txt"],
hashes.SHA1(),
)
diff --git a/tests/hazmat/primitives/test_pkcs12.py b/tests/hazmat/primitives/test_pkcs12.py
index f084d57..297483e 100644
--- a/tests/hazmat/primitives/test_pkcs12.py
+++ b/tests/hazmat/primitives/test_pkcs12.py
@@ -10,61 +10,85 @@
from cryptography import x509
from cryptography.hazmat.backends.interfaces import DERSerializationBackend
+from cryptography.hazmat.backends.openssl.backend import _RC2
+from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives.serialization.pkcs12 import (
- load_key_and_certificates
+ load_key_and_certificates,
+ serialize_key_and_certificates,
)
from .utils import load_vectors_from_file
+from ...doubles import DummyKeySerializationEncryption
@pytest.mark.requires_backend_interface(interface=DERSerializationBackend)
-class TestPKCS12(object):
- @pytest.mark.parametrize(
- ("filename", "password"),
- [
- ("cert-key-aes256cbc.p12", b"cryptography"),
- ("cert-none-key-none.p12", b"cryptography"),
- ("cert-rc2-key-3des.p12", b"cryptography"),
- ("no-password.p12", None),
- ]
- )
- def test_load_pkcs12_ec_keys(self, filename, password, backend):
+class TestPKCS12Loading(object):
+ def _test_load_pkcs12_ec_keys(self, filename, password, backend):
cert = load_vectors_from_file(
os.path.join("x509", "custom", "ca", "ca.pem"),
lambda pemfile: x509.load_pem_x509_certificate(
pemfile.read(), backend
- ), mode="rb"
+ ),
+ mode="rb",
)
key = load_vectors_from_file(
os.path.join("x509", "custom", "ca", "ca_key.pem"),
lambda pemfile: load_pem_private_key(
pemfile.read(), None, backend
- ), mode="rb"
+ ),
+ mode="rb",
)
parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file(
os.path.join("pkcs12", filename),
lambda derfile: load_key_and_certificates(
derfile.read(), password, backend
- ), mode="rb"
+ ),
+ mode="rb",
)
assert parsed_cert == cert
assert parsed_key.private_numbers() == key.private_numbers()
assert parsed_more_certs == []
+ @pytest.mark.parametrize(
+ ("filename", "password"),
+ [
+ ("cert-key-aes256cbc.p12", b"cryptography"),
+ ("cert-none-key-none.p12", b"cryptography"),
+ ],
+ )
+ def test_load_pkcs12_ec_keys(self, filename, password, backend):
+ self._test_load_pkcs12_ec_keys(filename, password, backend)
+
+ @pytest.mark.parametrize(
+ ("filename", "password"),
+ [
+ ("cert-rc2-key-3des.p12", b"cryptography"),
+ ("no-password.p12", None),
+ ],
+ )
+ @pytest.mark.supported(
+ only_if=lambda backend: backend.cipher_supported(_RC2(), None),
+ skip_message="Does not support RC2",
+ )
+ @pytest.mark.skip_fips(reason="Unsupported algorithm in FIPS mode")
+ def test_load_pkcs12_ec_keys_rc2(self, filename, password, backend):
+ self._test_load_pkcs12_ec_keys(filename, password, backend)
+
def test_load_pkcs12_cert_only(self, backend):
cert = load_vectors_from_file(
os.path.join("x509", "custom", "ca", "ca.pem"),
lambda pemfile: x509.load_pem_x509_certificate(
pemfile.read(), backend
- ), mode="rb"
+ ),
+ mode="rb",
)
parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file(
os.path.join("pkcs12", "cert-aes256cbc-no-key.p12"),
lambda data: load_key_and_certificates(
data.read(), b"cryptography", backend
),
- mode="rb"
+ mode="rb",
)
assert parsed_cert is None
assert parsed_key is None
@@ -75,14 +99,15 @@
os.path.join("x509", "custom", "ca", "ca_key.pem"),
lambda pemfile: load_pem_private_key(
pemfile.read(), None, backend
- ), mode="rb"
+ ),
+ mode="rb",
)
parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file(
os.path.join("pkcs12", "no-cert-key-aes256cbc.p12"),
lambda data: load_key_and_certificates(
data.read(), b"cryptography", backend
),
- mode="rb"
+ mode="rb",
)
assert parsed_key.private_numbers() == key.private_numbers()
assert parsed_cert is None
@@ -90,15 +115,11 @@
def test_non_bytes(self, backend):
with pytest.raises(TypeError):
- load_key_and_certificates(
- b"irrelevant", object(), backend
- )
+ load_key_and_certificates(b"irrelevant", object(), backend)
def test_not_a_pkcs12(self, backend):
with pytest.raises(ValueError):
- load_key_and_certificates(
- b"invalid", b"pass", backend
- )
+ load_key_and_certificates(b"invalid", b"pass", backend)
def test_invalid_password(self, backend):
with pytest.raises(ValueError):
@@ -106,13 +127,15 @@
os.path.join("pkcs12", "cert-key-aes256cbc.p12"),
lambda derfile: load_key_and_certificates(
derfile.read(), b"invalid", backend
- ), mode="rb"
+ ),
+ mode="rb",
)
def test_buffer_protocol(self, backend):
p12 = load_vectors_from_file(
os.path.join("pkcs12", "cert-key-aes256cbc.p12"),
- lambda derfile: derfile.read(), mode="rb"
+ lambda derfile: derfile.read(),
+ mode="rb",
)
p12buffer = bytearray(p12)
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
@@ -121,3 +144,128 @@
assert parsed_key is not None
assert parsed_cert is not None
assert parsed_more_certs == []
+
+
+def _load_cert(backend, path):
+ return load_vectors_from_file(
+ path,
+ lambda pemfile: x509.load_pem_x509_certificate(
+ pemfile.read(), backend
+ ),
+ mode="rb",
+ )
+
+
+def _load_ca(backend):
+ cert = _load_cert(backend, os.path.join("x509", "custom", "ca", "ca.pem"))
+ key = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "ca_key.pem"),
+ lambda pemfile: load_pem_private_key(pemfile.read(), None, backend),
+ mode="rb",
+ )
+ return cert, key
+
+
+class TestPKCS12Creation(object):
+ @pytest.mark.parametrize("name", [None, b"name"])
+ @pytest.mark.parametrize(
+ ("encryption_algorithm", "password"),
+ [
+ (serialization.BestAvailableEncryption(b"password"), b"password"),
+ (serialization.NoEncryption(), None),
+ ],
+ )
+ def test_generate(self, backend, name, encryption_algorithm, password):
+ cert, key = _load_ca(backend)
+ p12 = serialize_key_and_certificates(
+ name, key, cert, None, encryption_algorithm
+ )
+
+ parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
+ p12, password, backend
+ )
+ assert parsed_cert == cert
+ assert parsed_key.private_numbers() == key.private_numbers()
+ assert parsed_more_certs == []
+
+ def test_generate_with_cert_key_ca(self, backend):
+ cert, key = _load_ca(backend)
+ cert2 = _load_cert(
+ backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem")
+ )
+ cert3 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem"))
+ encryption = serialization.NoEncryption()
+ p12 = serialize_key_and_certificates(
+ None, key, cert, [cert2, cert3], encryption
+ )
+
+ parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
+ p12, None, backend
+ )
+ assert parsed_cert == cert
+ assert parsed_key.private_numbers() == key.private_numbers()
+ assert parsed_more_certs == [cert2, cert3]
+
+ def test_generate_wrong_types(self, backend):
+ cert, key = _load_ca(backend)
+ cert2 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem"))
+ encryption = serialization.NoEncryption()
+ with pytest.raises(TypeError) as exc:
+ serialize_key_and_certificates(
+ b"name", cert, cert, None, encryption
+ )
+ assert (
+ str(exc.value)
+ == "Key must be RSA, DSA, or EllipticCurve private key."
+ )
+
+ with pytest.raises(TypeError) as exc:
+ serialize_key_and_certificates(b"name", key, key, None, encryption)
+ assert str(exc.value) == "cert must be a certificate"
+
+ with pytest.raises(TypeError) as exc:
+ serialize_key_and_certificates(b"name", key, cert, None, key)
+ assert str(exc.value) == (
+ "Key encryption algorithm must be a "
+ "KeySerializationEncryption instance"
+ )
+
+ with pytest.raises(TypeError) as exc:
+ serialize_key_and_certificates(None, key, cert, cert2, encryption)
+
+ with pytest.raises(TypeError) as exc:
+ serialize_key_and_certificates(None, key, cert, [key], encryption)
+ assert str(exc.value) == "all values in cas must be certificates"
+
+ def test_generate_no_cert(self, backend):
+ _, key = _load_ca(backend)
+ p12 = serialize_key_and_certificates(
+ None, key, None, None, serialization.NoEncryption()
+ )
+ parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
+ p12, None, backend
+ )
+ assert parsed_cert is None
+ assert parsed_key.private_numbers() == key.private_numbers()
+ assert parsed_more_certs == []
+
+ def test_must_supply_something(self):
+ with pytest.raises(ValueError) as exc:
+ serialize_key_and_certificates(
+ None, None, None, None, serialization.NoEncryption()
+ )
+ assert str(exc.value) == (
+ "You must supply at least one of key, cert, or cas"
+ )
+
+ def test_generate_unsupported_encryption_type(self, backend):
+ cert, key = _load_ca(backend)
+ with pytest.raises(ValueError) as exc:
+ serialize_key_and_certificates(
+ None,
+ key,
+ cert,
+ None,
+ DummyKeySerializationEncryption(),
+ )
+ assert str(exc.value) == "Unsupported key encryption type"
diff --git a/tests/hazmat/primitives/test_pkcs7.py b/tests/hazmat/primitives/test_pkcs7.py
new file mode 100644
index 0000000..8b93cb6
--- /dev/null
+++ b/tests/hazmat/primitives/test_pkcs7.py
@@ -0,0 +1,675 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from __future__ import absolute_import, division, print_function
+
+import os
+
+import pytest
+
+from cryptography import x509
+from cryptography.exceptions import _Reasons
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import ed25519
+from cryptography.hazmat.primitives.serialization import pkcs7
+
+from .utils import load_vectors_from_file
+from ...utils import raises_unsupported_algorithm
+
+
+class TestPKCS7Loading(object):
+ def test_load_invalid_der_pkcs7(self):
+ with pytest.raises(ValueError):
+ pkcs7.load_der_pkcs7_certificates(b"nonsense")
+
+ def test_load_invalid_pem_pkcs7(self):
+ with pytest.raises(ValueError):
+ pkcs7.load_pem_pkcs7_certificates(b"nonsense")
+
+ def test_not_bytes_der(self):
+ with pytest.raises(TypeError):
+ pkcs7.load_der_pkcs7_certificates(38)
+
+ def test_not_bytes_pem(self):
+ with pytest.raises(TypeError):
+ pkcs7.load_pem_pkcs7_certificates(38)
+
+ def test_load_pkcs7_pem(self):
+ certs = load_vectors_from_file(
+ os.path.join("pkcs7", "isrg.pem"),
+ lambda pemfile: pkcs7.load_pem_pkcs7_certificates(pemfile.read()),
+ mode="rb",
+ )
+ assert len(certs) == 1
+ assert certs[0].subject.get_attributes_for_oid(
+ x509.oid.NameOID.COMMON_NAME
+ ) == [
+ x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u"ISRG Root X1")
+ ]
+
+ def test_load_pkcs7_der(self):
+ certs = load_vectors_from_file(
+ os.path.join("pkcs7", "amazon-roots.p7b"),
+ lambda derfile: pkcs7.load_der_pkcs7_certificates(derfile.read()),
+ mode="rb",
+ )
+ assert len(certs) == 2
+ assert certs[0].subject.get_attributes_for_oid(
+ x509.oid.NameOID.COMMON_NAME
+ ) == [
+ x509.NameAttribute(
+ x509.oid.NameOID.COMMON_NAME, u"Amazon Root CA 3"
+ )
+ ]
+ assert certs[1].subject.get_attributes_for_oid(
+ x509.oid.NameOID.COMMON_NAME
+ ) == [
+ x509.NameAttribute(
+ x509.oid.NameOID.COMMON_NAME, u"Amazon Root CA 2"
+ )
+ ]
+
+ def test_load_pkcs7_unsupported_type(self):
+ with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_SERIALIZATION):
+ load_vectors_from_file(
+ os.path.join("pkcs7", "enveloped.pem"),
+ lambda pemfile: pkcs7.load_pem_pkcs7_certificates(
+ pemfile.read()
+ ),
+ mode="rb",
+ )
+
+
+# We have no public verification API and won't be adding one until we get
+# some requirements from users so this function exists to give us basic
+# verification for the signing tests.
+def _pkcs7_verify(encoding, sig, msg, certs, options, backend):
+ sig_bio = backend._bytes_to_bio(sig)
+ if encoding is serialization.Encoding.DER:
+ p7 = backend._lib.d2i_PKCS7_bio(sig_bio.bio, backend._ffi.NULL)
+ elif encoding is serialization.Encoding.PEM:
+ p7 = backend._lib.PEM_read_bio_PKCS7(
+ sig_bio.bio,
+ backend._ffi.NULL,
+ backend._ffi.NULL,
+ backend._ffi.NULL,
+ )
+ else:
+ p7 = backend._lib.SMIME_read_PKCS7(sig_bio.bio, backend._ffi.NULL)
+ backend.openssl_assert(p7 != backend._ffi.NULL)
+ p7 = backend._ffi.gc(p7, backend._lib.PKCS7_free)
+ flags = 0
+ for option in options:
+ if option is pkcs7.PKCS7Options.Text:
+ flags |= backend._lib.PKCS7_TEXT
+ store = backend._lib.X509_STORE_new()
+ backend.openssl_assert(store != backend._ffi.NULL)
+ store = backend._ffi.gc(store, backend._lib.X509_STORE_free)
+ for cert in certs:
+ res = backend._lib.X509_STORE_add_cert(store, cert._x509)
+ backend.openssl_assert(res == 1)
+ if msg is None:
+ res = backend._lib.PKCS7_verify(
+ p7,
+ backend._ffi.NULL,
+ store,
+ backend._ffi.NULL,
+ backend._ffi.NULL,
+ flags,
+ )
+ else:
+ msg_bio = backend._bytes_to_bio(msg)
+ res = backend._lib.PKCS7_verify(
+ p7, backend._ffi.NULL, store, msg_bio.bio, backend._ffi.NULL, flags
+ )
+ backend.openssl_assert(res == 1)
+
+
+def _load_cert_key():
+ key = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "ca_key.pem"),
+ lambda pemfile: serialization.load_pem_private_key(
+ pemfile.read(), None
+ ),
+ mode="rb",
+ )
+ cert = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "ca.pem"),
+ loader=lambda pemfile: x509.load_pem_x509_certificate(pemfile.read()),
+ mode="rb",
+ )
+ return cert, key
+
+
+class TestPKCS7Builder(object):
+ def test_invalid_data(self):
+ builder = pkcs7.PKCS7SignatureBuilder()
+ with pytest.raises(TypeError):
+ builder.set_data(u"not bytes")
+
+ def test_set_data_twice(self):
+ builder = pkcs7.PKCS7SignatureBuilder().set_data(b"test")
+ with pytest.raises(ValueError):
+ builder.set_data(b"test")
+
+ def test_sign_no_signer(self):
+ builder = pkcs7.PKCS7SignatureBuilder().set_data(b"test")
+ with pytest.raises(ValueError):
+ builder.sign(serialization.Encoding.SMIME, [])
+
+ def test_sign_no_data(self):
+ cert, key = _load_cert_key()
+ builder = pkcs7.PKCS7SignatureBuilder().add_signer(
+ cert, key, hashes.SHA256()
+ )
+ with pytest.raises(ValueError):
+ builder.sign(serialization.Encoding.SMIME, [])
+
+ def test_unsupported_hash_alg(self):
+ cert, key = _load_cert_key()
+ with pytest.raises(TypeError):
+ pkcs7.PKCS7SignatureBuilder().add_signer(
+ cert, key, hashes.SHA512_256()
+ )
+
+ def test_not_a_cert(self):
+ cert, key = _load_cert_key()
+ with pytest.raises(TypeError):
+ pkcs7.PKCS7SignatureBuilder().add_signer(
+ b"notacert", key, hashes.SHA256()
+ )
+
+ @pytest.mark.supported(
+ only_if=lambda backend: backend.ed25519_supported(),
+ skip_message="Does not support ed25519.",
+ )
+ def test_unsupported_key_type(self, backend):
+ cert, _ = _load_cert_key()
+ key = ed25519.Ed25519PrivateKey.generate()
+ with pytest.raises(TypeError):
+ pkcs7.PKCS7SignatureBuilder().add_signer(
+ cert, key, hashes.SHA256()
+ )
+
+ def test_sign_invalid_options(self):
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(b"test")
+ .add_signer(cert, key, hashes.SHA256())
+ )
+ with pytest.raises(ValueError):
+ builder.sign(serialization.Encoding.SMIME, [b"invalid"])
+
+ def test_sign_invalid_encoding(self):
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(b"test")
+ .add_signer(cert, key, hashes.SHA256())
+ )
+ with pytest.raises(ValueError):
+ builder.sign(serialization.Encoding.Raw, [])
+
+ def test_sign_invalid_options_text_no_detached(self):
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(b"test")
+ .add_signer(cert, key, hashes.SHA256())
+ )
+ options = [pkcs7.PKCS7Options.Text]
+ with pytest.raises(ValueError):
+ builder.sign(serialization.Encoding.SMIME, options)
+
+ def test_sign_invalid_options_text_der_encoding(self):
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(b"test")
+ .add_signer(cert, key, hashes.SHA256())
+ )
+ options = [
+ pkcs7.PKCS7Options.Text,
+ pkcs7.PKCS7Options.DetachedSignature,
+ ]
+ with pytest.raises(ValueError):
+ builder.sign(serialization.Encoding.DER, options)
+
+ def test_sign_invalid_options_no_attrs_and_no_caps(self):
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(b"test")
+ .add_signer(cert, key, hashes.SHA256())
+ )
+ options = [
+ pkcs7.PKCS7Options.NoAttributes,
+ pkcs7.PKCS7Options.NoCapabilities,
+ ]
+ with pytest.raises(ValueError):
+ builder.sign(serialization.Encoding.SMIME, options)
+
+ def test_smime_sign_detached(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ options = [pkcs7.PKCS7Options.DetachedSignature]
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ sig = builder.sign(serialization.Encoding.SMIME, options)
+ sig_binary = builder.sign(serialization.Encoding.DER, options)
+ # We don't have a generic ASN.1 parser available to us so we instead
+ # will assert on specific byte sequences being present based on the
+ # parameters chosen above.
+ assert b"sha-256" in sig
+ # Detached signature means that the signed data is *not* embedded into
+ # the PKCS7 structure itself, but is present in the SMIME serialization
+ # as a separate section before the PKCS7 data. So we should expect to
+ # have data in sig but not in sig_binary
+ assert data in sig
+ _pkcs7_verify(
+ serialization.Encoding.SMIME, sig, data, [cert], options, backend
+ )
+ assert data not in sig_binary
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig_binary,
+ data,
+ [cert],
+ options,
+ backend,
+ )
+
+ def test_sign_byteslike(self):
+ data = bytearray(b"hello world")
+ cert, key = _load_cert_key()
+ options = [pkcs7.PKCS7Options.DetachedSignature]
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ sig = builder.sign(serialization.Encoding.SMIME, options)
+ assert bytes(data) in sig
+
+ def test_sign_pem(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ options = []
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ sig = builder.sign(serialization.Encoding.PEM, options)
+ _pkcs7_verify(
+ serialization.Encoding.PEM,
+ sig,
+ None,
+ [cert],
+ options,
+ backend,
+ )
+
+ @pytest.mark.parametrize(
+ ("hash_alg", "expected_value"),
+ [
+ (hashes.SHA1(), b"\x06\x05+\x0e\x03\x02\x1a"),
+ (hashes.SHA256(), b"\x06\t`\x86H\x01e\x03\x04\x02\x01"),
+ (hashes.SHA384(), b"\x06\t`\x86H\x01e\x03\x04\x02\x02"),
+ (hashes.SHA512(), b"\x06\t`\x86H\x01e\x03\x04\x02\x03"),
+ ],
+ )
+ def test_sign_alternate_digests_der(
+ self, hash_alg, expected_value, backend
+ ):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hash_alg)
+ )
+ options = []
+ sig = builder.sign(serialization.Encoding.DER, options)
+ assert expected_value in sig
+ _pkcs7_verify(
+ serialization.Encoding.DER, sig, None, [cert], options, backend
+ )
+
+ @pytest.mark.parametrize(
+ ("hash_alg", "expected_value"),
+ [
+ (hashes.SHA1(), b"sha1"),
+ (hashes.SHA256(), b"sha-256"),
+ (hashes.SHA384(), b"sha-384"),
+ (hashes.SHA512(), b"sha-512"),
+ ],
+ )
+ def test_sign_alternate_digests_detached(self, hash_alg, expected_value):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hash_alg)
+ )
+ options = [pkcs7.PKCS7Options.DetachedSignature]
+ sig = builder.sign(serialization.Encoding.SMIME, options)
+ # When in detached signature mode the hash algorithm is stored as a
+ # byte string like "sha-384".
+ assert expected_value in sig
+
+ def test_sign_attached(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ options = []
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ sig_binary = builder.sign(serialization.Encoding.DER, options)
+ # When not passing detached signature the signed data is embedded into
+ # the PKCS7 structure itself
+ assert data in sig_binary
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig_binary,
+ None,
+ [cert],
+ options,
+ backend,
+ )
+
+ def test_sign_binary(self, backend):
+ data = b"hello\nworld"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+ options = []
+ sig_no_binary = builder.sign(serialization.Encoding.DER, options)
+ sig_binary = builder.sign(
+ serialization.Encoding.DER, [pkcs7.PKCS7Options.Binary]
+ )
+ # Binary prevents translation of LF to CR+LF (SMIME canonical form)
+ # so data should not be present in sig_no_binary, but should be present
+ # in sig_binary
+ assert data not in sig_no_binary
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig_no_binary,
+ None,
+ [cert],
+ options,
+ backend,
+ )
+ assert data in sig_binary
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig_binary,
+ None,
+ [cert],
+ options,
+ backend,
+ )
+
+ def test_sign_smime_canonicalization(self, backend):
+ data = b"hello\nworld"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ options = []
+ sig_binary = builder.sign(serialization.Encoding.DER, options)
+ # LF gets converted to CR+LF (SMIME canonical form)
+ # so data should not be present in the sig
+ assert data not in sig_binary
+ assert b"hello\r\nworld" in sig_binary
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig_binary,
+ None,
+ [cert],
+ options,
+ backend,
+ )
+
+ def test_sign_text(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ options = [
+ pkcs7.PKCS7Options.Text,
+ pkcs7.PKCS7Options.DetachedSignature,
+ ]
+ sig_pem = builder.sign(serialization.Encoding.SMIME, options)
+ # The text option adds text/plain headers to the S/MIME message
+ # These headers are only relevant in SMIME mode, not binary, which is
+ # just the PKCS7 structure itself.
+ assert b"text/plain" in sig_pem
+ # When passing the Text option the header is prepended so the actual
+ # signed data is this.
+ signed_data = b"Content-Type: text/plain\r\n\r\nhello world"
+ _pkcs7_verify(
+ serialization.Encoding.SMIME,
+ sig_pem,
+ signed_data,
+ [cert],
+ options,
+ backend,
+ )
+
+ def test_sign_no_capabilities(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ options = [pkcs7.PKCS7Options.NoCapabilities]
+ sig_binary = builder.sign(serialization.Encoding.DER, options)
+ # NoCapabilities removes the SMIMECapabilities attribute from the
+ # PKCS7 structure. This is an ASN.1 sequence with the
+ # OID 1.2.840.113549.1.9.15. It does NOT remove all authenticated
+ # attributes, so we verify that by looking for the signingTime OID.
+
+ # 1.2.840.113549.1.9.15 SMIMECapabilities as an ASN.1 DER encoded OID
+ assert b"\x06\t*\x86H\x86\xf7\r\x01\t\x0f" not in sig_binary
+ # 1.2.840.113549.1.9.5 signingTime as an ASN.1 DER encoded OID
+ assert b"\x06\t*\x86H\x86\xf7\r\x01\t\x05" in sig_binary
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig_binary,
+ None,
+ [cert],
+ options,
+ backend,
+ )
+
+ def test_sign_no_attributes(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ options = [pkcs7.PKCS7Options.NoAttributes]
+ sig_binary = builder.sign(serialization.Encoding.DER, options)
+ # NoAttributes removes all authenticated attributes, so we shouldn't
+ # find SMIMECapabilities or signingTime.
+
+ # 1.2.840.113549.1.9.15 SMIMECapabilities as an ASN.1 DER encoded OID
+ assert b"\x06\t*\x86H\x86\xf7\r\x01\t\x0f" not in sig_binary
+ # 1.2.840.113549.1.9.5 signingTime as an ASN.1 DER encoded OID
+ assert b"\x06\t*\x86H\x86\xf7\r\x01\t\x05" not in sig_binary
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig_binary,
+ None,
+ [cert],
+ options,
+ backend,
+ )
+
+ def test_sign_no_certs(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA256())
+ )
+
+ options = []
+ sig = builder.sign(serialization.Encoding.DER, options)
+ assert sig.count(cert.public_bytes(serialization.Encoding.DER)) == 1
+
+ options = [pkcs7.PKCS7Options.NoCerts]
+ sig_no = builder.sign(serialization.Encoding.DER, options)
+ assert sig_no.count(cert.public_bytes(serialization.Encoding.DER)) == 0
+
+ def test_multiple_signers(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ rsa_key = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "rsa_key.pem"),
+ lambda pemfile: serialization.load_pem_private_key(
+ pemfile.read(), None
+ ),
+ mode="rb",
+ )
+ rsa_cert = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "rsa_ca.pem"),
+ loader=lambda pemfile: x509.load_pem_x509_certificate(
+ pemfile.read()
+ ),
+ mode="rb",
+ )
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA512())
+ .add_signer(rsa_cert, rsa_key, hashes.SHA512())
+ )
+ options = []
+ sig = builder.sign(serialization.Encoding.DER, options)
+ # There should be three SHA512 OIDs in this structure
+ assert sig.count(b"\x06\t`\x86H\x01e\x03\x04\x02\x03") == 3
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig,
+ None,
+ [cert, rsa_cert],
+ options,
+ backend,
+ )
+
+ def test_multiple_signers_different_hash_algs(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ rsa_key = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "rsa_key.pem"),
+ lambda pemfile: serialization.load_pem_private_key(
+ pemfile.read(), None
+ ),
+ mode="rb",
+ )
+ rsa_cert = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "rsa_ca.pem"),
+ loader=lambda pemfile: x509.load_pem_x509_certificate(
+ pemfile.read()
+ ),
+ mode="rb",
+ )
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA384())
+ .add_signer(rsa_cert, rsa_key, hashes.SHA512())
+ )
+ options = []
+ sig = builder.sign(serialization.Encoding.DER, options)
+ # There should be two SHA384 and two SHA512 OIDs in this structure
+ assert sig.count(b"\x06\t`\x86H\x01e\x03\x04\x02\x02") == 2
+ assert sig.count(b"\x06\t`\x86H\x01e\x03\x04\x02\x03") == 2
+ _pkcs7_verify(
+ serialization.Encoding.DER,
+ sig,
+ None,
+ [cert, rsa_cert],
+ options,
+ backend,
+ )
+
+ def test_add_additional_cert_not_a_cert(self, backend):
+ with pytest.raises(TypeError):
+ pkcs7.PKCS7SignatureBuilder().add_certificate(b"notacert")
+
+ def test_add_additional_cert(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ rsa_cert = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "rsa_ca.pem"),
+ loader=lambda pemfile: x509.load_pem_x509_certificate(
+ pemfile.read()
+ ),
+ mode="rb",
+ )
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA384())
+ .add_certificate(rsa_cert)
+ )
+ options = []
+ sig = builder.sign(serialization.Encoding.DER, options)
+ assert (
+ sig.count(rsa_cert.public_bytes(serialization.Encoding.DER)) == 1
+ )
+
+ def test_add_multiple_additional_certs(self, backend):
+ data = b"hello world"
+ cert, key = _load_cert_key()
+ rsa_cert = load_vectors_from_file(
+ os.path.join("x509", "custom", "ca", "rsa_ca.pem"),
+ loader=lambda pemfile: x509.load_pem_x509_certificate(
+ pemfile.read()
+ ),
+ mode="rb",
+ )
+ builder = (
+ pkcs7.PKCS7SignatureBuilder()
+ .set_data(data)
+ .add_signer(cert, key, hashes.SHA384())
+ .add_certificate(rsa_cert)
+ .add_certificate(rsa_cert)
+ )
+ options = []
+ sig = builder.sign(serialization.Encoding.DER, options)
+ assert (
+ sig.count(rsa_cert.public_bytes(serialization.Encoding.DER)) == 2
+ )
diff --git a/tests/hazmat/primitives/test_poly1305.py b/tests/hazmat/primitives/test_poly1305.py
new file mode 100644
index 0000000..8779484
--- /dev/null
+++ b/tests/hazmat/primitives/test_poly1305.py
@@ -0,0 +1,156 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from __future__ import absolute_import, division, print_function
+
+import binascii
+import os
+
+import pytest
+
+from cryptography.exceptions import (
+ AlreadyFinalized,
+ InvalidSignature,
+ _Reasons,
+)
+from cryptography.hazmat.primitives.poly1305 import Poly1305
+
+from ...utils import (
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
+)
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: not backend.poly1305_supported(),
+ skip_message="Requires OpenSSL without poly1305 support",
+)
+def test_poly1305_unsupported(backend):
+ with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_MAC):
+ Poly1305(b"0" * 32)
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: backend.poly1305_supported(),
+ skip_message="Requires OpenSSL with poly1305 support",
+)
+class TestPoly1305(object):
+ @pytest.mark.parametrize(
+ "vector",
+ load_vectors_from_file(
+ os.path.join("poly1305", "rfc7539.txt"), load_nist_vectors
+ ),
+ )
+ def test_vectors(self, vector, backend):
+ key = binascii.unhexlify(vector["key"])
+ msg = binascii.unhexlify(vector["msg"])
+ tag = binascii.unhexlify(vector["tag"])
+ poly = Poly1305(key)
+ poly.update(msg)
+ assert poly.finalize() == tag
+
+ assert Poly1305.generate_tag(key, msg) == tag
+ Poly1305.verify_tag(key, msg, tag)
+
+ def test_key_with_no_additional_references(self, backend):
+ poly = Poly1305(os.urandom(32))
+ assert len(poly.finalize()) == 16
+
+ def test_raises_after_finalize(self, backend):
+ poly = Poly1305(b"0" * 32)
+ poly.finalize()
+
+ with pytest.raises(AlreadyFinalized):
+ poly.update(b"foo")
+
+ with pytest.raises(AlreadyFinalized):
+ poly.finalize()
+
+ def test_reject_unicode(self, backend):
+ poly = Poly1305(b"0" * 32)
+ with pytest.raises(TypeError):
+ poly.update(u"")
+
+ with pytest.raises(TypeError):
+ Poly1305.generate_tag(b"0" * 32, u"")
+
+ def test_verify(self, backend):
+ poly = Poly1305(b"0" * 32)
+ poly.update(b"msg")
+ tag = poly.finalize()
+
+ with pytest.raises(AlreadyFinalized):
+ poly.verify(b"")
+
+ poly2 = Poly1305(b"0" * 32)
+ poly2.update(b"msg")
+ poly2.verify(tag)
+
+ Poly1305.verify_tag(b"0" * 32, b"msg", tag)
+
+ def test_invalid_verify(self, backend):
+ poly = Poly1305(b"0" * 32)
+ poly.update(b"msg")
+ with pytest.raises(InvalidSignature):
+ poly.verify(b"")
+
+ p2 = Poly1305(b"0" * 32)
+ p2.update(b"msg")
+ with pytest.raises(InvalidSignature):
+ p2.verify(b"\x00" * 16)
+
+ with pytest.raises(InvalidSignature):
+ Poly1305.verify_tag(b"0" * 32, b"msg", b"\x00" * 16)
+
+ def test_verify_reject_unicode(self, backend):
+ poly = Poly1305(b"0" * 32)
+ with pytest.raises(TypeError):
+ poly.verify(u"")
+
+ with pytest.raises(TypeError):
+ Poly1305.verify_tag(b"0" * 32, b"msg", u"")
+
+ def test_invalid_key_type(self, backend):
+ with pytest.raises(TypeError):
+ Poly1305(object())
+
+ with pytest.raises(TypeError):
+ Poly1305.generate_tag(object(), b"msg")
+
+ def test_invalid_key_length(self, backend):
+ with pytest.raises(ValueError):
+ Poly1305(b"0" * 31)
+
+ with pytest.raises(ValueError):
+ Poly1305.generate_tag(b"0" * 31, b"msg")
+
+ with pytest.raises(ValueError):
+ Poly1305(b"0" * 33)
+
+ with pytest.raises(ValueError):
+ Poly1305.generate_tag(b"0" * 33, b"msg")
+
+ def test_buffer_protocol(self, backend):
+ key = binascii.unhexlify(
+ b"1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cb"
+ b"c207075c0"
+ )
+ msg = binascii.unhexlify(
+ b"2754776173206272696c6c69672c20616e642074686520736c69746"
+ b"87920746f7665730a446964206779726520616e642067696d626c65"
+ b"20696e2074686520776162653a0a416c6c206d696d7379207765726"
+ b"52074686520626f726f676f7665732c0a416e6420746865206d6f6d"
+ b"65207261746873206f757467726162652e"
+ )
+ key = bytearray(key)
+ poly = Poly1305(key)
+ poly.update(bytearray(msg))
+ assert poly.finalize() == binascii.unhexlify(
+ b"4541669a7eaaee61e708dc7cbcc5eb62"
+ )
+
+ assert Poly1305.generate_tag(key, msg) == binascii.unhexlify(
+ b"4541669a7eaaee61e708dc7cbcc5eb62"
+ )
diff --git a/tests/hazmat/primitives/test_rsa.py b/tests/hazmat/primitives/test_rsa.py
index 65d88f5..61c4815 100644
--- a/tests/hazmat/primitives/test_rsa.py
+++ b/tests/hazmat/primitives/test_rsa.py
@@ -6,41 +6,67 @@
import binascii
import itertools
-import math
import os
import pytest
from cryptography.exceptions import (
- AlreadyFinalized, InvalidSignature, _Reasons
+ AlreadyFinalized,
+ InvalidSignature,
+ _Reasons,
)
from cryptography.hazmat.backends.interfaces import (
- PEMSerializationBackend, RSABackend
+ PEMSerializationBackend,
+ RSABackend,
)
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import (
- padding, rsa, utils as asym_utils
+ padding,
+ rsa,
+ utils as asym_utils,
)
from cryptography.hazmat.primitives.asymmetric.rsa import (
- RSAPrivateNumbers, RSAPublicNumbers
+ RSAPrivateNumbers,
+ RSAPublicNumbers,
)
from cryptography.utils import CryptographyDeprecationWarning
from .fixtures_rsa import (
- RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027, RSA_KEY_1028,
- RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031, RSA_KEY_1536, RSA_KEY_2048,
- RSA_KEY_2048_ALT, RSA_KEY_512, RSA_KEY_512_ALT, RSA_KEY_522, RSA_KEY_599,
- RSA_KEY_745, RSA_KEY_768,
+ RSA_KEY_1024,
+ RSA_KEY_1025,
+ RSA_KEY_1026,
+ RSA_KEY_1027,
+ RSA_KEY_1028,
+ RSA_KEY_1029,
+ RSA_KEY_1030,
+ RSA_KEY_1031,
+ RSA_KEY_1536,
+ RSA_KEY_2048,
+ RSA_KEY_2048_ALT,
+ RSA_KEY_512,
+ RSA_KEY_512_ALT,
+ RSA_KEY_522,
+ RSA_KEY_599,
+ RSA_KEY_745,
+ RSA_KEY_768,
+ RSA_KEY_CORRUPTED,
)
from .utils import (
- _check_rsa_private_numbers, generate_rsa_verification_test
+ _check_rsa_private_numbers,
+ generate_rsa_verification_test,
+ skip_fips_traditional_openssl,
)
from ...doubles import (
- DummyAsymmetricPadding, DummyHashAlgorithm, DummyKeySerializationEncryption
+ DummyAsymmetricPadding,
+ DummyHashAlgorithm,
+ DummyKeySerializationEncryption,
)
from ...utils import (
- load_nist_vectors, load_pkcs1_vectors, load_rsa_nist_vectors,
- load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_pkcs1_vectors,
+ load_rsa_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
@@ -89,11 +115,9 @@
load_vectors_from_file(
os.path.join(
base_path,
- "oaep-{0}-{1}.txt".format(
- mgf1alg.name, oaepalg.name
- )
+ "oaep-{}-{}.txt".format(mgf1alg.name, oaepalg.name),
),
- load_pkcs1_vectors
+ load_pkcs1_vectors,
)
)
# We've loaded the files, but the loaders don't give us any information
@@ -107,12 +131,11 @@
def _skip_pss_hash_algorithm_unsupported(backend, hash_alg):
if not backend.rsa_padding_supported(
padding.PSS(
- mgf=padding.MGF1(hash_alg),
- salt_length=padding.PSS.MAX_LENGTH
+ mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.MAX_LENGTH
)
):
pytest.skip(
- "Does not support {0} in MGF1 using PSS.".format(hash_alg.name)
+ "Does not support {} in MGF1 using PSS.".format(hash_alg.name)
)
@@ -127,19 +150,22 @@
"d1f9f6c09fd3d38987f7970247b85a6da84907753d42ec52bc23b745093f4fff5cff3"
"617ce43d00121a9accc0051f519c76e08cf02fc18acfe4c9e6aea18da470a2b611d2e"
"56a7b35caa2c0239bc041a53cc5875ca0b668ae6377d4b23e932d8c995fd1e58ecfd8"
- "c4b73259c0d8a54d691cca3f6fb85c8a5c1baf588e898d481", 16
+ "c4b73259c0d8a54d691cca3f6fb85c8a5c1baf588e898d481",
+ 16,
)
q = int(
"d1519255eb8f678c86cfd06802d1fbef8b664441ac46b73d33d13a8404580a33a8e74"
"cb2ea2e2963125b3d454d7a922cef24dd13e55f989cbabf64255a736671f4629a47b5"
"b2347cfcd669133088d1c159518531025297c2d67c9da856a12e80222cd03b4c6ec0f"
- "86c957cb7bb8de7a127b645ec9e820aa94581e4762e209f01", 16
+ "86c957cb7bb8de7a127b645ec9e820aa94581e4762e209f01",
+ 16,
)
assert rsa._modinv(q, p) == int(
"0275e06afa722999315f8f322275483e15e2fb46d827b17800f99110b269a6732748f"
"624a382fa2ed1ec68c99f7fc56fb60e76eea51614881f497ba7034c17dde955f92f15"
"772f8b2b41f3e56d88b1e096cdd293eba4eae1e82db815e0fadea0c4ec971bc6fd875"
- "c20e67e48c31a611e98d32c6213ae4c4d7b53023b2f80c538", 16
+ "c20e67e48c31a611e98d32c6213ae4c4d7b53023b2f80c538",
+ 16,
)
@@ -148,11 +174,18 @@
@pytest.mark.parametrize(
("public_exponent", "key_size"),
itertools.product(
- (3, 5, 65537),
- (1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1536, 2048)
- )
+ (3, 65537),
+ (1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1536, 2048),
+ ),
)
def test_generate_rsa_keys(self, backend, public_exponent, key_size):
+ if backend._fips_enabled:
+ if key_size < backend._fips_rsa_min_key_size:
+ pytest.skip("Key size not FIPS compliant: {}".format(key_size))
+ if public_exponent < backend._fips_rsa_min_public_exponent:
+ pytest.skip(
+ "Exponent not FIPS compliant: {}".format(public_exponent)
+ )
skey = rsa.generate_private_key(public_exponent, key_size, backend)
assert skey.key_size == key_size
@@ -162,33 +195,39 @@
def test_generate_bad_public_exponent(self, backend):
with pytest.raises(ValueError):
- rsa.generate_private_key(public_exponent=1,
- key_size=2048,
- backend=backend)
+ rsa.generate_private_key(
+ public_exponent=1, key_size=2048, backend=backend
+ )
with pytest.raises(ValueError):
- rsa.generate_private_key(public_exponent=4,
- key_size=2048,
- backend=backend)
+ rsa.generate_private_key(
+ public_exponent=4, key_size=2048, backend=backend
+ )
+
+ with pytest.raises(ValueError):
+ rsa.generate_private_key(
+ public_exponent=65535, key_size=2048, backend=backend
+ )
def test_cant_generate_insecure_tiny_key(self, backend):
with pytest.raises(ValueError):
- rsa.generate_private_key(public_exponent=65537,
- key_size=511,
- backend=backend)
+ rsa.generate_private_key(
+ public_exponent=65537, key_size=511, backend=backend
+ )
with pytest.raises(ValueError):
- rsa.generate_private_key(public_exponent=65537,
- key_size=256,
- backend=backend)
+ rsa.generate_private_key(
+ public_exponent=65537, key_size=256, backend=backend
+ )
@pytest.mark.parametrize(
"pkcs1_example",
load_vectors_from_file(
os.path.join(
- "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"),
- load_pkcs1_vectors
- )
+ "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"
+ ),
+ load_pkcs1_vectors,
+ ),
)
def test_load_pss_vect_example_keys(self, pkcs1_example):
secret, public = pkcs1_example
@@ -201,15 +240,13 @@
dmq1=secret["dmq1"],
iqmp=secret["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
- e=secret["public_exponent"],
- n=secret["modulus"]
- )
+ e=secret["public_exponent"], n=secret["modulus"]
+ ),
)
_check_rsa_private_numbers(private_num)
public_num = rsa.RSAPublicNumbers(
- e=public["public_exponent"],
- n=public["modulus"]
+ e=public["public_exponent"], n=public["modulus"]
)
assert public_num
@@ -223,17 +260,18 @@
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "RSA", "oaep-label.txt"),
- load_nist_vectors)
+ load_nist_vectors,
+ ),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=b"label"
+ label=b"label",
)
),
- skip_message="Does not support RSA OAEP labels"
+ skip_message="Does not support RSA OAEP labels",
)
def test_oaep_label_decrypt(self, vector, backend):
private_key = serialization.load_der_private_key(
@@ -245,8 +283,8 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA512()),
algorithm=hashes.SHA512(),
- label=binascii.unhexlify(vector["oaeplabel"])
- )
+ label=binascii.unhexlify(vector["oaeplabel"]),
+ ),
)
assert vector["output"][1:-1] == decrypted
@@ -255,17 +293,17 @@
[
(b"amazing encrypted msg", b"some label"),
(b"amazing encrypted msg", b""),
- ]
+ ],
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=b"label"
+ label=b"label",
)
),
- skip_message="Does not support RSA OAEP labels"
+ skip_message="Does not support RSA OAEP labels",
)
def test_oaep_label_roundtrip(self, msg, label, backend):
private_key = RSA_KEY_2048.private_key(backend)
@@ -274,54 +312,52 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=label
- )
+ label=label,
+ ),
)
pt = private_key.decrypt(
ct,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=label
- )
+ label=label,
+ ),
)
assert pt == msg
@pytest.mark.parametrize(
("enclabel", "declabel"),
- [
- (b"label1", b"label2"),
- (b"label3", b""),
- (b"", b"label4"),
- ]
+ [(b"label1", b"label2"), (b"label3", b""), (b"", b"label4")],
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=b"label"
+ label=b"label",
)
),
- skip_message="Does not support RSA OAEP labels"
+ skip_message="Does not support RSA OAEP labels",
)
def test_oaep_wrong_label(self, enclabel, declabel, backend):
private_key = RSA_KEY_2048.private_key(backend)
msg = b"test"
ct = private_key.public_key().encrypt(
- msg, padding.OAEP(
+ msg,
+ padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=enclabel
- )
+ label=enclabel,
+ ),
)
with pytest.raises(ValueError):
private_key.decrypt(
- ct, padding.OAEP(
+ ct,
+ padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=declabel
- )
+ label=declabel,
+ ),
)
@pytest.mark.supported(
@@ -329,10 +365,10 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
- label=b"label"
+ label=b"label",
)
),
- skip_message="Requires backend without RSA OAEP label support"
+ skip_message="Requires backend without RSA OAEP label support",
)
def test_unsupported_oaep_label_decrypt(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -342,8 +378,8 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=b"label"
- )
+ label=b"label",
+ ),
)
@@ -360,15 +396,16 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.parametrize(
"pkcs1_example",
- _flatten_pkcs1_examples(load_vectors_from_file(
- os.path.join(
- "asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
- load_pkcs1_vectors
- ))
+ _flatten_pkcs1_examples(
+ load_vectors_from_file(
+ os.path.join("asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
+ load_pkcs1_vectors,
+ )
+ ),
)
def test_pkcs1v15_signing(self, pkcs1_example, backend):
private, public, example = pkcs1_example
@@ -380,14 +417,13 @@
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
- e=private["public_exponent"],
- n=private["modulus"]
- )
+ e=private["public_exponent"], n=private["modulus"]
+ ),
).private_key(backend)
signature = private_key.sign(
binascii.unhexlify(example["message"]),
padding.PKCS1v15(),
- hashes.SHA1()
+ hashes.SHA1(),
)
assert binascii.hexlify(signature) == example["signature"]
@@ -395,18 +431,21 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
@pytest.mark.parametrize(
"pkcs1_example",
- _flatten_pkcs1_examples(load_vectors_from_file(
- os.path.join(
- "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"),
- load_pkcs1_vectors
- ))
+ _flatten_pkcs1_examples(
+ load_vectors_from_file(
+ os.path.join(
+ "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"
+ ),
+ load_pkcs1_vectors,
+ )
+ ),
)
def test_pss_signing(self, pkcs1_example, backend):
private, public, example = pkcs1_example
@@ -418,23 +457,21 @@
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
- e=private["public_exponent"],
- n=private["modulus"]
- )
+ e=private["public_exponent"], n=private["modulus"]
+ ),
).private_key(backend)
public_key = rsa.RSAPublicNumbers(
- e=public["public_exponent"],
- n=public["modulus"]
+ e=public["public_exponent"], n=public["modulus"]
).public_key(backend)
signature = private_key.sign(
binascii.unhexlify(example["message"]),
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
- hashes.SHA1()
+ hashes.SHA1(),
)
- assert len(signature) == math.ceil(private_key.key_size / 8.0)
+ assert len(signature) == (private_key.key_size + 7) // 8
# PSS signatures contain randomness so we can't do an exact
# signature check. Instead we'll verify that the signature created
# successfully verifies.
@@ -443,22 +480,21 @@
binascii.unhexlify(example["message"]),
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA1(),
)
@pytest.mark.parametrize(
"hash_alg",
- [hashes.SHA224(), hashes.SHA256(), hashes.SHA384(), hashes.SHA512()]
+ [hashes.SHA224(), hashes.SHA256(), hashes.SHA384(), hashes.SHA512()],
)
def test_pss_signing_sha2(self, hash_alg, backend):
_skip_pss_hash_algorithm_unsupported(backend, hash_alg)
private_key = RSA_KEY_768.private_key(backend)
public_key = private_key.public_key()
pss = padding.PSS(
- mgf=padding.MGF1(hash_alg),
- salt_length=padding.PSS.MAX_LENGTH
+ mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.MAX_LENGTH
)
msg = b"testing signature"
signature = private_key.sign(msg, pss, hash_alg)
@@ -466,15 +502,15 @@
@pytest.mark.supported(
only_if=lambda backend: (
- backend.hash_supported(hashes.SHA512()) and
- backend.rsa_padding_supported(
+ backend.hash_supported(hashes.SHA512())
+ and backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
)
),
- skip_message="Does not support SHA512."
+ skip_message="Does not support SHA512.",
)
def test_pss_minimum_key_size_for_digest(self, backend):
private_key = RSA_KEY_522.private_key(backend)
@@ -482,23 +518,23 @@
b"no failure",
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
- hashes.SHA512()
+ hashes.SHA512(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA512()),
- skip_message="Does not support SHA512."
+ skip_message="Does not support SHA512.",
)
def test_pss_signing_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -507,19 +543,19 @@
b"msg",
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
- hashes.SHA512()
+ hashes.SHA512(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_pss_signing_salt_length_too_long(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -527,17 +563,16 @@
private_key.sign(
b"failure coming",
padding.PSS(
- mgf=padding.MGF1(hashes.SHA1()),
- salt_length=1000000
+ mgf=padding.MGF1(hashes.SHA1()), salt_length=1000000
),
- hashes.SHA1()
+ hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_use_after_finalize(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -564,7 +599,7 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_unsupported_pss_mgf(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -572,40 +607,33 @@
private_key.sign(
b"msg",
padding.PSS(
- mgf=DummyMGF(),
- salt_length=padding.PSS.MAX_LENGTH
+ mgf=DummyMGF(), salt_length=padding.PSS.MAX_LENGTH
),
- hashes.SHA1()
+ hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_pkcs1_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_599.private_key(backend)
with pytest.raises(ValueError):
private_key.sign(
- b"failure coming",
- padding.PKCS1v15(),
- hashes.SHA512()
+ b"failure coming", padding.PKCS1v15(), hashes.SHA512()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_pkcs1_minimum_key_size(self, backend):
private_key = RSA_KEY_745.private_key(backend)
- private_key.sign(
- b"no failure",
- padding.PKCS1v15(),
- hashes.SHA512()
- )
+ private_key.sign(b"no failure", padding.PKCS1v15(), hashes.SHA512())
def test_sign(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -620,7 +648,7 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_prehashed_sign(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -636,14 +664,15 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
- hashes.BLAKE2s(digest_size=32)),
+ hashes.BLAKE2s(digest_size=32)
+ ),
skip_message="Does not support BLAKE2s",
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_unsupported_hash(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -656,7 +685,7 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_prehashed_digest_mismatch(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -673,31 +702,50 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_prehashed_unsupported_in_signer_ctx(self, backend):
private_key = RSA_KEY_512.private_key(backend)
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
private_key.signer(
- padding.PKCS1v15(),
- asym_utils.Prehashed(hashes.SHA1())
+ padding.PKCS1v15(), asym_utils.Prehashed(hashes.SHA1())
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_prehashed_unsupported_in_verifier_ctx(self, backend):
public_key = RSA_KEY_512.private_key(backend).public_key()
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
public_key.verifier(
b"0" * 64,
padding.PKCS1v15(),
- asym_utils.Prehashed(hashes.SHA1())
+ asym_utils.Prehashed(hashes.SHA1()),
+ )
+
+ def test_prehashed_unsupported_in_signature_recover(self, backend):
+ private_key = RSA_KEY_512.private_key(backend)
+ public_key = private_key.public_key()
+ signature = private_key.sign(
+ b"sign me", padding.PKCS1v15(), hashes.SHA1()
+ )
+ prehashed_alg = asym_utils.Prehashed(hashes.SHA1())
+ with pytest.raises(TypeError):
+ public_key.recover_data_from_signature(
+ signature, padding.PKCS1v15(), prehashed_alg
+ )
+
+ def test_corrupted_private_key(self, backend):
+ with pytest.raises(ValueError):
+ serialization.load_pem_private_key(
+ RSA_KEY_CORRUPTED, password=None, backend=backend
)
@@ -707,34 +755,49 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.parametrize(
"pkcs1_example",
- _flatten_pkcs1_examples(load_vectors_from_file(
- os.path.join(
- "asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
- load_pkcs1_vectors
- ))
+ _flatten_pkcs1_examples(
+ load_vectors_from_file(
+ os.path.join("asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
+ load_pkcs1_vectors,
+ )
+ ),
)
def test_pkcs1v15_verification(self, pkcs1_example, backend):
private, public, example = pkcs1_example
public_key = rsa.RSAPublicNumbers(
- e=public["public_exponent"],
- n=public["modulus"]
+ e=public["public_exponent"], n=public["modulus"]
).public_key(backend)
+ signature = binascii.unhexlify(example["signature"])
+ message = binascii.unhexlify(example["message"])
public_key.verify(
- binascii.unhexlify(example["signature"]),
- binascii.unhexlify(example["message"]),
- padding.PKCS1v15(),
- hashes.SHA1()
+ signature, message, padding.PKCS1v15(), hashes.SHA1()
)
+ # Test digest recovery by providing hash
+ digest = hashes.Hash(hashes.SHA1())
+ digest.update(message)
+ msg_digest = digest.finalize()
+ rec_msg_digest = public_key.recover_data_from_signature(
+ signature, padding.PKCS1v15(), hashes.SHA1()
+ )
+ assert msg_digest == rec_msg_digest
+
+ # Test recovery of all data (full DigestInfo) with hash alg. as None
+ rec_sig_data = public_key.recover_data_from_signature(
+ signature, padding.PKCS1v15(), None
+ )
+ assert len(rec_sig_data) > len(msg_digest)
+ assert msg_digest == rec_sig_data[-len(msg_digest) :]
+
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_invalid_pkcs1v15_signature_wrong_data(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -744,10 +807,18 @@
)
with pytest.raises(InvalidSignature):
public_key.verify(
- signature,
- b"incorrect data",
- padding.PKCS1v15(),
- hashes.SHA1()
+ signature, b"incorrect data", padding.PKCS1v15(), hashes.SHA1()
+ )
+
+ def test_invalid_pkcs1v15_signature_recover_wrong_hash_alg(self, backend):
+ private_key = RSA_KEY_512.private_key(backend)
+ public_key = private_key.public_key()
+ signature = private_key.sign(
+ b"sign me", padding.PKCS1v15(), hashes.SHA1()
+ )
+ with pytest.raises(InvalidSignature):
+ public_key.recover_data_from_signature(
+ signature, padding.PKCS1v15(), hashes.SHA256()
)
def test_invalid_signature_sequence_removed(self, backend):
@@ -782,14 +853,14 @@
sig,
binascii.unhexlify(b"313233343030"),
padding.PKCS1v15(),
- hashes.SHA256()
+ hashes.SHA256(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_invalid_pkcs1v15_signature_wrong_key(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -804,54 +875,53 @@
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
- padding.PSS(
- mgf=padding.MGF1(hashes.SHA1()),
- salt_length=20
- )
+ padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=20)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
@pytest.mark.parametrize(
"pkcs1_example",
- _flatten_pkcs1_examples(load_vectors_from_file(
- os.path.join(
- "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"),
- load_pkcs1_vectors
- ))
+ _flatten_pkcs1_examples(
+ load_vectors_from_file(
+ os.path.join(
+ "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"
+ ),
+ load_pkcs1_vectors,
+ )
+ ),
)
def test_pss_verification(self, pkcs1_example, backend):
private, public, example = pkcs1_example
public_key = rsa.RSAPublicNumbers(
- e=public["public_exponent"],
- n=public["modulus"]
+ e=public["public_exponent"], n=public["modulus"]
).public_key(backend)
public_key.verify(
binascii.unhexlify(example["signature"]),
binascii.unhexlify(example["message"]),
padding.PSS(
- mgf=padding.MGF1(algorithm=hashes.SHA1()),
- salt_length=20
+ mgf=padding.MGF1(algorithm=hashes.SHA1()), salt_length=20
),
- hashes.SHA1()
+ hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_invalid_pss_signature_wrong_data(self, backend):
public_key = rsa.RSAPublicNumbers(
n=int(
b"dffc2137d5e810cde9e4b4612f5796447218bab913b3fa98bdf7982e4fa6"
b"ec4d6653ef2b29fb1642b095befcbea6decc178fb4bed243d3c3592c6854"
- b"6af2d3f3", 16
+ b"6af2d3f3",
+ 16,
),
- e=65537
+ e=65537,
).public_key(backend)
signature = binascii.unhexlify(
b"0e68c3649df91c5bc3665f96e157efa75b71934aaa514d91e94ca8418d100f45"
@@ -863,19 +933,19 @@
b"incorrect data",
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
- hashes.SHA1()
+ hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_invalid_pss_signature_wrong_key(self, backend):
signature = binascii.unhexlify(
@@ -888,9 +958,10 @@
b"5a95441be90866a14c4d2e139cd16db540ec6c7abab13ffff91443fd46a8"
b"960cbb7658ded26a5c95c86f6e40384e1c1239c63e541ba221191c4dd303"
b"231b42e33c6dbddf5ec9a746f09bf0c25d0f8d27f93ee0ae5c0d723348f4"
- b"030d3581e13522e1", 16
+ b"030d3581e13522e1",
+ 16,
),
- e=65537
+ e=65537,
).public_key(backend)
with pytest.raises(InvalidSignature):
public_key.verify(
@@ -898,51 +969,71 @@
b"sign me",
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
- hashes.SHA1()
+ hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_invalid_pss_signature_data_too_large_for_modulus(self, backend):
+ # 2048 bit PSS signature
signature = binascii.unhexlify(
- b"cb43bde4f7ab89eb4a79c6e8dd67e0d1af60715da64429d90c716a490b799c29"
- b"194cf8046509c6ed851052367a74e2e92d9b38947ed74332acb115a03fcc0222"
+ b"58750fc3d2f560d1f3e37c8e28bc8da6d3e93f5d58f8becd25b1c931eea30fea"
+ b"54cb17d44b90104a0aacb7fe9ffa2a59c5788435911d63de78178d21eb875ccd"
+ b"0b07121b641ed4fe6bcb1ca5060322765507b4f24bdba8a698a8e4e07e6bf2c4"
+ b"7a736abe5a912e85cd32f648f3e043b4385e8b612dcce342c5fddf18c524deb5"
+ b"6295b95f6dfa759b2896b793628a90f133e74c1ff7d3af43e3f7ee792df2e5b6"
+ b"a19e996ac3676884354899a437b3ae4e3ac91976c336c332a3b1db0d172b19cb"
+ b"40ad3d871296cfffb3c889ce74a179a3e290852c35d59525afe4b39dc907fad2"
+ b"ac462c50a488dca486031a3dc8c4cdbbc53e9f71d64732e1533a5d1249b833ce"
)
- public_key = rsa.RSAPublicNumbers(
- n=int(
- b"381201f4905d67dfeb3dec131a0fbea773489227ec7a1448c3109189ac68"
- b"5a95441be90866a14c4d2e139cd16db540ec6c7abab13ffff91443fd46a8"
- b"960cbb7658ded26a5c95c86f6e40384e1c1239c63e541ba221191c4dd303"
- b"231b42e33c6dbddf5ec9a746f09bf0c25d0f8d27f93ee0ae5c0d723348f4"
- b"030d3581e13522", 16
- ),
- e=65537
- ).public_key(backend)
+ # 1024 bit key
+ public_key = RSA_KEY_1024.private_key(backend).public_key()
with pytest.raises(InvalidSignature):
public_key.verify(
signature,
b"sign me",
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
- hashes.SHA1()
+ hashes.SHA1(),
+ )
+
+ def test_invalid_pss_signature_recover(self, backend):
+ private_key = RSA_KEY_1024.private_key(backend)
+ public_key = private_key.public_key()
+ pss_padding = padding.PSS(
+ mgf=padding.MGF1(algorithm=hashes.SHA1()),
+ salt_length=padding.PSS.MAX_LENGTH,
+ )
+ signature = private_key.sign(b"sign me", pss_padding, hashes.SHA1())
+
+ # Hash algorithm can not be absent for PSS padding
+ with pytest.raises(TypeError):
+ public_key.recover_data_from_signature(
+ signature, pss_padding, None
+ )
+
+ # Signature data recovery not supported with PSS
+ with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
+ public_key.recover_data_from_signature(
+ signature, pss_padding, hashes.SHA1()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_use_after_finalize(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -953,9 +1044,7 @@
with pytest.warns(CryptographyDeprecationWarning):
verifier = public_key.verifier(
- signature,
- padding.PKCS1v15(),
- hashes.SHA1()
+ signature, padding.PKCS1v15(), hashes.SHA1()
)
verifier.update(b"sign me")
verifier.verify()
@@ -976,19 +1065,16 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_signature_not_bytes(self, backend):
public_key = RSA_KEY_512.public_numbers.public_key(backend)
signature = 1234
- with pytest.raises(TypeError), \
- pytest.warns(CryptographyDeprecationWarning):
- public_key.verifier(
- signature,
- padding.PKCS1v15(),
- hashes.SHA1()
- )
+ with pytest.raises(TypeError), pytest.warns(
+ CryptographyDeprecationWarning
+ ):
+ public_key.verifier(signature, padding.PKCS1v15(), hashes.SHA1())
def test_padding_incorrect_type(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -1000,7 +1086,7 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_unsupported_pss_mgf(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -1010,24 +1096,23 @@
b"sig",
b"msg",
padding.PSS(
- mgf=DummyMGF(),
- salt_length=padding.PSS.MAX_LENGTH
+ mgf=DummyMGF(), salt_length=padding.PSS.MAX_LENGTH
),
- hashes.SHA1()
+ hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA512()),
- skip_message="Does not support SHA512."
+ skip_message="Does not support SHA512.",
)
def test_pss_verify_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -1042,19 +1127,19 @@
b"msg doesn't matter",
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
),
- hashes.SHA512()
+ hashes.SHA512(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS."
+ skip_message="Does not support PSS.",
)
def test_pss_verify_salt_length_too_long(self, backend):
signature = binascii.unhexlify(
@@ -1065,9 +1150,10 @@
n=int(
b"d309e4612809437548b747d7f9eb9cd3340f54fe42bb3f84a36933b0839c"
b"11b0c8b7f67e11f7252370161e31159c49c784d4bc41c42a78ce0f0b40a3"
- b"ca8ffb91", 16
+ b"ca8ffb91",
+ 16,
),
- e=65537
+ e=65537,
).public_key(backend)
with pytest.raises(InvalidSignature):
public_key.verify(
@@ -1077,9 +1163,9 @@
mgf=padding.MGF1(
algorithm=hashes.SHA1(),
),
- salt_length=1000000
+ salt_length=1000000,
),
- hashes.SHA1()
+ hashes.SHA1(),
)
def test_verify(self, backend):
@@ -1121,219 +1207,239 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS using MGF1 with SHA1."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGenPSS_186-2.rsp",
- "SigGenPSS_186-3.rsp",
- "SigVerPSS_186-3.rsp",
- ],
- hashes.SHA1(),
- lambda params, hash_alg: padding.PSS(
- mgf=padding.MGF1(
- algorithm=hash_alg,
+ skip_message="Does not support PSS using MGF1 with SHA1.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGenPSS_186-2.rsp",
+ "SigGenPSS_186-3.rsp",
+ "SigVerPSS_186-3.rsp",
+ ],
+ hashes.SHA1(),
+ lambda params, hash_alg: padding.PSS(
+ mgf=padding.MGF1(
+ algorithm=hash_alg,
+ ),
+ salt_length=params["salt_length"],
),
- salt_length=params["salt_length"]
)
- ))
+ )
test_rsa_pss_mgf1_sha224 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA224()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS using MGF1 with SHA224."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGenPSS_186-2.rsp",
- "SigGenPSS_186-3.rsp",
- "SigVerPSS_186-3.rsp",
- ],
- hashes.SHA224(),
- lambda params, hash_alg: padding.PSS(
- mgf=padding.MGF1(
- algorithm=hash_alg,
+ skip_message="Does not support PSS using MGF1 with SHA224.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGenPSS_186-2.rsp",
+ "SigGenPSS_186-3.rsp",
+ "SigVerPSS_186-3.rsp",
+ ],
+ hashes.SHA224(),
+ lambda params, hash_alg: padding.PSS(
+ mgf=padding.MGF1(
+ algorithm=hash_alg,
+ ),
+ salt_length=params["salt_length"],
),
- salt_length=params["salt_length"]
)
- ))
+ )
test_rsa_pss_mgf1_sha256 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS using MGF1 with SHA256."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGenPSS_186-2.rsp",
- "SigGenPSS_186-3.rsp",
- "SigVerPSS_186-3.rsp",
- ],
- hashes.SHA256(),
- lambda params, hash_alg: padding.PSS(
- mgf=padding.MGF1(
- algorithm=hash_alg,
+ skip_message="Does not support PSS using MGF1 with SHA256.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGenPSS_186-2.rsp",
+ "SigGenPSS_186-3.rsp",
+ "SigVerPSS_186-3.rsp",
+ ],
+ hashes.SHA256(),
+ lambda params, hash_alg: padding.PSS(
+ mgf=padding.MGF1(
+ algorithm=hash_alg,
+ ),
+ salt_length=params["salt_length"],
),
- salt_length=params["salt_length"]
)
- ))
+ )
test_rsa_pss_mgf1_sha384 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA384()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS using MGF1 with SHA384."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGenPSS_186-2.rsp",
- "SigGenPSS_186-3.rsp",
- "SigVerPSS_186-3.rsp",
- ],
- hashes.SHA384(),
- lambda params, hash_alg: padding.PSS(
- mgf=padding.MGF1(
- algorithm=hash_alg,
+ skip_message="Does not support PSS using MGF1 with SHA384.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGenPSS_186-2.rsp",
+ "SigGenPSS_186-3.rsp",
+ "SigVerPSS_186-3.rsp",
+ ],
+ hashes.SHA384(),
+ lambda params, hash_alg: padding.PSS(
+ mgf=padding.MGF1(
+ algorithm=hash_alg,
+ ),
+ salt_length=params["salt_length"],
),
- salt_length=params["salt_length"]
)
- ))
+ )
test_rsa_pss_mgf1_sha512 = pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA512()),
- salt_length=padding.PSS.MAX_LENGTH
+ salt_length=padding.PSS.MAX_LENGTH,
)
),
- skip_message="Does not support PSS using MGF1 with SHA512."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGenPSS_186-2.rsp",
- "SigGenPSS_186-3.rsp",
- "SigVerPSS_186-3.rsp",
- ],
- hashes.SHA512(),
- lambda params, hash_alg: padding.PSS(
- mgf=padding.MGF1(
- algorithm=hash_alg,
+ skip_message="Does not support PSS using MGF1 with SHA512.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGenPSS_186-2.rsp",
+ "SigGenPSS_186-3.rsp",
+ "SigVerPSS_186-3.rsp",
+ ],
+ hashes.SHA512(),
+ lambda params, hash_alg: padding.PSS(
+ mgf=padding.MGF1(
+ algorithm=hash_alg,
+ ),
+ salt_length=params["salt_length"],
),
- salt_length=params["salt_length"]
)
- ))
+ )
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSAPKCS1Verification(object):
test_rsa_pkcs1v15_verify_sha1 = pytest.mark.supported(
only_if=lambda backend: (
- backend.hash_supported(hashes.SHA1()) and
- backend.rsa_padding_supported(padding.PKCS1v15())
+ backend.hash_supported(hashes.SHA1())
+ and backend.rsa_padding_supported(padding.PKCS1v15())
),
- skip_message="Does not support SHA1 and PKCS1v1.5."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGen15_186-2.rsp",
- "SigGen15_186-3.rsp",
- "SigVer15_186-3.rsp",
- ],
- hashes.SHA1(),
- lambda params, hash_alg: padding.PKCS1v15()
- ))
+ skip_message="Does not support SHA1 and PKCS1v1.5.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGen15_186-2.rsp",
+ "SigGen15_186-3.rsp",
+ "SigVer15_186-3.rsp",
+ ],
+ hashes.SHA1(),
+ lambda params, hash_alg: padding.PKCS1v15(),
+ )
+ )
test_rsa_pkcs1v15_verify_sha224 = pytest.mark.supported(
only_if=lambda backend: (
- backend.hash_supported(hashes.SHA224()) and
- backend.rsa_padding_supported(padding.PKCS1v15())
+ backend.hash_supported(hashes.SHA224())
+ and backend.rsa_padding_supported(padding.PKCS1v15())
),
- skip_message="Does not support SHA224 and PKCS1v1.5."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGen15_186-2.rsp",
- "SigGen15_186-3.rsp",
- "SigVer15_186-3.rsp",
- ],
- hashes.SHA224(),
- lambda params, hash_alg: padding.PKCS1v15()
- ))
+ skip_message="Does not support SHA224 and PKCS1v1.5.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGen15_186-2.rsp",
+ "SigGen15_186-3.rsp",
+ "SigVer15_186-3.rsp",
+ ],
+ hashes.SHA224(),
+ lambda params, hash_alg: padding.PKCS1v15(),
+ )
+ )
test_rsa_pkcs1v15_verify_sha256 = pytest.mark.supported(
only_if=lambda backend: (
- backend.hash_supported(hashes.SHA256()) and
- backend.rsa_padding_supported(padding.PKCS1v15())
+ backend.hash_supported(hashes.SHA256())
+ and backend.rsa_padding_supported(padding.PKCS1v15())
),
- skip_message="Does not support SHA256 and PKCS1v1.5."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGen15_186-2.rsp",
- "SigGen15_186-3.rsp",
- "SigVer15_186-3.rsp",
- ],
- hashes.SHA256(),
- lambda params, hash_alg: padding.PKCS1v15()
- ))
+ skip_message="Does not support SHA256 and PKCS1v1.5.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGen15_186-2.rsp",
+ "SigGen15_186-3.rsp",
+ "SigVer15_186-3.rsp",
+ ],
+ hashes.SHA256(),
+ lambda params, hash_alg: padding.PKCS1v15(),
+ )
+ )
test_rsa_pkcs1v15_verify_sha384 = pytest.mark.supported(
only_if=lambda backend: (
- backend.hash_supported(hashes.SHA384()) and
- backend.rsa_padding_supported(padding.PKCS1v15())
+ backend.hash_supported(hashes.SHA384())
+ and backend.rsa_padding_supported(padding.PKCS1v15())
),
- skip_message="Does not support SHA384 and PKCS1v1.5."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGen15_186-2.rsp",
- "SigGen15_186-3.rsp",
- "SigVer15_186-3.rsp",
- ],
- hashes.SHA384(),
- lambda params, hash_alg: padding.PKCS1v15()
- ))
+ skip_message="Does not support SHA384 and PKCS1v1.5.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGen15_186-2.rsp",
+ "SigGen15_186-3.rsp",
+ "SigVer15_186-3.rsp",
+ ],
+ hashes.SHA384(),
+ lambda params, hash_alg: padding.PKCS1v15(),
+ )
+ )
test_rsa_pkcs1v15_verify_sha512 = pytest.mark.supported(
only_if=lambda backend: (
- backend.hash_supported(hashes.SHA512()) and
- backend.rsa_padding_supported(padding.PKCS1v15())
+ backend.hash_supported(hashes.SHA512())
+ and backend.rsa_padding_supported(padding.PKCS1v15())
),
- skip_message="Does not support SHA512 and PKCS1v1.5."
- )(generate_rsa_verification_test(
- load_rsa_nist_vectors,
- os.path.join("asymmetric", "RSA", "FIPS_186-2"),
- [
- "SigGen15_186-2.rsp",
- "SigGen15_186-3.rsp",
- "SigVer15_186-3.rsp",
- ],
- hashes.SHA512(),
- lambda params, hash_alg: padding.PKCS1v15()
- ))
+ skip_message="Does not support SHA512 and PKCS1v1.5.",
+ )(
+ generate_rsa_verification_test(
+ load_rsa_nist_vectors,
+ os.path.join("asymmetric", "RSA", "FIPS_186-2"),
+ [
+ "SigGen15_186-2.rsp",
+ "SigGen15_186-3.rsp",
+ "SigVer15_186-3.rsp",
+ ],
+ hashes.SHA512(),
+ lambda params, hash_alg: padding.PKCS1v15(),
+ )
+ )
class TestPSS(object):
@@ -1344,20 +1450,12 @@
def test_invalid_salt_length_not_integer(self):
with pytest.raises(TypeError):
padding.PSS(
- mgf=padding.MGF1(
- hashes.SHA1()
- ),
- salt_length=b"not_a_length"
+ mgf=padding.MGF1(hashes.SHA1()), salt_length=b"not_a_length"
)
def test_invalid_salt_length_negative_integer(self):
with pytest.raises(ValueError):
- padding.PSS(
- mgf=padding.MGF1(
- hashes.SHA1()
- ),
- salt_length=-1
- )
+ padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=-1)
def test_valid_pss_parameters(self):
algorithm = hashes.SHA1()
@@ -1390,11 +1488,7 @@
def test_invalid_algorithm(self):
mgf = padding.MGF1(hashes.SHA1())
with pytest.raises(TypeError):
- padding.OAEP(
- mgf=mgf,
- algorithm=b"",
- label=None
- )
+ padding.OAEP(mgf=mgf, algorithm=b"", label=None)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@@ -1403,15 +1497,16 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.parametrize(
"vector",
- _flatten_pkcs1_examples(load_vectors_from_file(
- os.path.join(
- "asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"),
- load_pkcs1_vectors
- ))
+ _flatten_pkcs1_examples(
+ load_vectors_from_file(
+ os.path.join("asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"),
+ load_pkcs1_vectors,
+ )
+ ),
)
def test_decrypt_pkcs1v15_vectors(self, vector, backend):
private, public, example = vector
@@ -1423,12 +1518,11 @@
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
- e=private["public_exponent"],
- n=private["modulus"]
- )
+ e=private["public_exponent"], n=private["modulus"]
+ ),
).private_key(backend)
ciphertext = binascii.unhexlify(example["encryption"])
- assert len(ciphertext) == math.ceil(skey.key_size / 8.0)
+ assert len(ciphertext) == (skey.key_size + 7) // 8
message = skey.decrypt(ciphertext, padding.PKCS1v15())
assert message == binascii.unhexlify(example["message"])
@@ -1441,35 +1535,29 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_decrypt_invalid_decrypt(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(ValueError):
- private_key.decrypt(
- b"\x00" * 64,
- padding.PKCS1v15()
- )
+ private_key.decrypt(b"\x00" * 64, padding.PKCS1v15())
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_decrypt_ciphertext_too_large(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(ValueError):
- private_key.decrypt(
- b"\x00" * 65,
- padding.PKCS1v15()
- )
+ private_key.decrypt(b"\x00" * 65, padding.PKCS1v15())
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
def test_decrypt_ciphertext_too_small(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -1478,28 +1566,28 @@
b"69d210f2b9bdfb48b12f9ea05009c77da257cc600ccefe3a6283789d8ea0"
)
with pytest.raises(ValueError):
- private_key.decrypt(
- ct,
- padding.PKCS1v15()
- )
+ private_key.decrypt(ct, padding.PKCS1v15())
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
+ label=None,
)
),
- skip_message="Does not support OAEP."
+ skip_message="Does not support OAEP.",
)
@pytest.mark.parametrize(
"vector",
- _flatten_pkcs1_examples(load_vectors_from_file(
- os.path.join(
- "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "oaep-vect.txt"),
- load_pkcs1_vectors
- ))
+ _flatten_pkcs1_examples(
+ load_vectors_from_file(
+ os.path.join(
+ "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "oaep-vect.txt"
+ ),
+ load_pkcs1_vectors,
+ )
+ ),
)
def test_decrypt_oaep_vectors(self, vector, backend):
private, public, example = vector
@@ -1511,17 +1599,16 @@
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
- e=private["public_exponent"],
- n=private["modulus"]
- )
+ e=private["public_exponent"], n=private["modulus"]
+ ),
).private_key(backend)
message = skey.decrypt(
binascii.unhexlify(example["encryption"]),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
- )
+ label=None,
+ ),
)
assert message == binascii.unhexlify(example["message"])
@@ -1530,15 +1617,14 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA224()),
algorithm=hashes.SHA224(),
- label=None
+ label=None,
)
),
- skip_message="Does not support OAEP using SHA224 MGF1 and SHA224 hash."
+ skip_message=(
+ "Does not support OAEP using SHA224 MGF1 and SHA224 hash."
+ ),
)
- @pytest.mark.parametrize(
- "vector",
- _build_oaep_sha2_vectors()
- )
+ @pytest.mark.parametrize("vector", _build_oaep_sha2_vectors())
def test_decrypt_oaep_sha2_vectors(self, vector, backend):
private, public, example, mgf1_alg, hash_alg = vector
skey = rsa.RSAPrivateNumbers(
@@ -1549,17 +1635,16 @@
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
- e=private["public_exponent"],
- n=private["modulus"]
- )
+ e=private["public_exponent"], n=private["modulus"]
+ ),
).private_key(backend)
message = skey.decrypt(
binascii.unhexlify(example["encryption"]),
padding.OAEP(
mgf=padding.MGF1(algorithm=mgf1_alg),
algorithm=hash_alg,
- label=None
- )
+ label=None,
+ ),
)
assert message == binascii.unhexlify(example["message"])
@@ -1568,24 +1653,24 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
+ label=None,
)
),
- skip_message="Does not support OAEP."
+ skip_message="Does not support OAEP.",
)
def test_invalid_oaep_decryption(self, backend):
- # More recent versions of OpenSSL may raise RSA_R_OAEP_DECODING_ERROR
- # This test triggers it and confirms that we properly handle it. Other
- # backends should also return the proper ValueError.
+ # More recent versions of OpenSSL may raise different errors.
+ # This test triggers a failure and confirms that we properly handle
+ # it.
private_key = RSA_KEY_512.private_key(backend)
ciphertext = private_key.public_key().encrypt(
- b'secure data',
+ b"secure data",
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
- )
+ label=None,
+ ),
)
private_key_alt = RSA_KEY_512_ALT.private_key(backend)
@@ -1596,8 +1681,8 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
- )
+ label=None,
+ ),
)
@pytest.mark.supported(
@@ -1605,27 +1690,27 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
+ label=None,
)
),
- skip_message="Does not support OAEP."
+ skip_message="Does not support OAEP.",
)
def test_invalid_oaep_decryption_data_to_large_for_modulus(self, backend):
key = RSA_KEY_2048_ALT.private_key(backend)
ciphertext = (
- b'\xb1ph\xc0\x0b\x1a|\xe6\xda\xea\xb5\xd7%\x94\x07\xf96\xfb\x96'
- b'\x11\x9b\xdc4\xea.-\x91\x80\x13S\x94\x04m\xe9\xc5/F\x1b\x9b:\\'
- b'\x1d\x04\x16ML\xae\xb32J\x01yuA\xbb\x83\x1c\x8f\xf6\xa5\xdbp\xcd'
- b'\nx\xc7\xf6\x15\xb2/\xdcH\xae\xe7\x13\x13by\r4t\x99\x0fc\x1f\xc1'
- b'\x1c\xb1\xdd\xc5\x08\xd1\xee\xa1XQ\xb8H@L5v\xc3\xaf\xf2\r\x97'
- b'\xed\xaa\xe7\xf1\xd4xai\xd3\x83\xd9\xaa9\xbfx\xe1\x87F \x01\xff'
- b'L\xccv}ae\xb3\xfa\xf2B\xb8\xf9\x04H\x94\x85\xcb\x86\xbb\\ghx!W31'
- b'\xc7;t\na_E\xc2\x16\xb0;\xa1\x18\t\x1b\xe1\xdb\x80>)\x15\xc6\x12'
- b'\xcb\xeeg`\x8b\x9b\x1b\x05y4\xb0\x84M6\xcd\xa1\x827o\xfd\x96\xba'
- b'Z#\x8d\xae\x01\xc9\xf2\xb6\xde\x89{8&eQ\x1e8\x03\x01#?\xb66\\'
- b'\xad.\xe9\xfa!\x95 c{\xcaz\xe0*\tP\r\x91\x9a)B\xb5\xadN\xf4$\x83'
- b'\t\xb5u\xab\x19\x99'
+ b"\xb1ph\xc0\x0b\x1a|\xe6\xda\xea\xb5\xd7%\x94\x07\xf96\xfb\x96"
+ b"\x11\x9b\xdc4\xea.-\x91\x80\x13S\x94\x04m\xe9\xc5/F\x1b\x9b:\\"
+ b"\x1d\x04\x16ML\xae\xb32J\x01yuA\xbb\x83\x1c\x8f\xf6\xa5\xdbp\xcd"
+ b"\nx\xc7\xf6\x15\xb2/\xdcH\xae\xe7\x13\x13by\r4t\x99\x0fc\x1f\xc1"
+ b"\x1c\xb1\xdd\xc5\x08\xd1\xee\xa1XQ\xb8H@L5v\xc3\xaf\xf2\r\x97"
+ b"\xed\xaa\xe7\xf1\xd4xai\xd3\x83\xd9\xaa9\xbfx\xe1\x87F \x01\xff"
+ b"L\xccv}ae\xb3\xfa\xf2B\xb8\xf9\x04H\x94\x85\xcb\x86\xbb\\ghx!W31"
+ b"\xc7;t\na_E\xc2\x16\xb0;\xa1\x18\t\x1b\xe1\xdb\x80>)\x15\xc6\x12"
+ b"\xcb\xeeg`\x8b\x9b\x1b\x05y4\xb0\x84M6\xcd\xa1\x827o\xfd\x96\xba"
+ b"Z#\x8d\xae\x01\xc9\xf2\xb6\xde\x89{8&eQ\x1e8\x03\x01#?\xb66\\"
+ b"\xad.\xe9\xfa!\x95 c{\xcaz\xe0*\tP\r\x91\x9a)B\xb5\xadN\xf4$\x83"
+ b"\t\xb5u\xab\x19\x99"
)
with pytest.raises(ValueError):
@@ -1634,8 +1719,8 @@
padding.OAEP(
algorithm=hashes.SHA1(),
mgf=padding.MGF1(hashes.SHA1()),
- label=None
- )
+ label=None,
+ ),
)
def test_unsupported_oaep_mgf(self, backend):
@@ -1644,10 +1729,8 @@
private_key.decrypt(
b"0" * 64,
padding.OAEP(
- mgf=DummyMGF(),
- algorithm=hashes.SHA1(),
- label=None
- )
+ mgf=DummyMGF(), algorithm=hashes.SHA1(), label=None
+ ),
)
@@ -1658,25 +1741,34 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
+ label=None,
)
),
- skip_message="Does not support OAEP."
+ skip_message="Does not support OAEP.",
)
@pytest.mark.parametrize(
("key_data", "pad"),
itertools.product(
- (RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027,
- RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031,
- RSA_KEY_1536, RSA_KEY_2048),
+ (
+ RSA_KEY_1024,
+ RSA_KEY_1025,
+ RSA_KEY_1026,
+ RSA_KEY_1027,
+ RSA_KEY_1028,
+ RSA_KEY_1029,
+ RSA_KEY_1030,
+ RSA_KEY_1031,
+ RSA_KEY_1536,
+ RSA_KEY_2048,
+ ),
[
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
+ label=None,
)
- ]
- )
+ ],
+ ),
)
def test_rsa_encrypt_oaep(self, key_data, pad, backend):
private_key = key_data.private_key(backend)
@@ -1684,7 +1776,7 @@
public_key = private_key.public_key()
ct = public_key.encrypt(pt, pad)
assert ct != pt
- assert len(ct) == math.ceil(public_key.key_size / 8.0)
+ assert len(ct) == (public_key.key_size + 7) // 8
recovered_pt = private_key.decrypt(ct, pad)
assert recovered_pt == pt
@@ -1693,39 +1785,44 @@
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA512(),
- label=None
+ label=None,
)
),
- skip_message="Does not support OAEP using SHA256 MGF1 and SHA512 hash."
+ skip_message=(
+ "Does not support OAEP using SHA256 MGF1 and SHA512 hash."
+ ),
)
@pytest.mark.parametrize(
("mgf1hash", "oaephash"),
- itertools.product([
- hashes.SHA1(),
- hashes.SHA224(),
- hashes.SHA256(),
- hashes.SHA384(),
- hashes.SHA512(),
- ], [
- hashes.SHA1(),
- hashes.SHA224(),
- hashes.SHA256(),
- hashes.SHA384(),
- hashes.SHA512(),
- ])
+ itertools.product(
+ [
+ hashes.SHA1(),
+ hashes.SHA224(),
+ hashes.SHA256(),
+ hashes.SHA384(),
+ hashes.SHA512(),
+ ],
+ [
+ hashes.SHA1(),
+ hashes.SHA224(),
+ hashes.SHA256(),
+ hashes.SHA384(),
+ hashes.SHA512(),
+ ],
+ ),
)
def test_rsa_encrypt_oaep_sha2(self, mgf1hash, oaephash, backend):
pad = padding.OAEP(
mgf=padding.MGF1(algorithm=mgf1hash),
algorithm=oaephash,
- label=None
+ label=None,
)
private_key = RSA_KEY_2048.private_key(backend)
pt = b"encrypt me using sha2 hashes!"
public_key = private_key.public_key()
ct = public_key.encrypt(pt, pad)
assert ct != pt
- assert len(ct) == math.ceil(public_key.key_size / 8.0)
+ assert len(ct) == (public_key.key_size + 7) // 8
recovered_pt = private_key.decrypt(ct, pad)
assert recovered_pt == pt
@@ -1733,16 +1830,25 @@
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
- skip_message="Does not support PKCS1v1.5."
+ skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.parametrize(
("key_data", "pad"),
itertools.product(
- (RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027,
- RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031,
- RSA_KEY_1536, RSA_KEY_2048),
- [padding.PKCS1v15()]
- )
+ (
+ RSA_KEY_1024,
+ RSA_KEY_1025,
+ RSA_KEY_1026,
+ RSA_KEY_1027,
+ RSA_KEY_1028,
+ RSA_KEY_1029,
+ RSA_KEY_1030,
+ RSA_KEY_1031,
+ RSA_KEY_1536,
+ RSA_KEY_2048,
+ ),
+ [padding.PKCS1v15()],
+ ),
)
def test_rsa_encrypt_pkcs1v15(self, key_data, pad, backend):
private_key = key_data.private_key(backend)
@@ -1750,42 +1856,45 @@
public_key = private_key.public_key()
ct = public_key.encrypt(pt, pad)
assert ct != pt
- assert len(ct) == math.ceil(public_key.key_size / 8.0)
+ assert len(ct) == (public_key.key_size + 7) // 8
recovered_pt = private_key.decrypt(ct, pad)
assert recovered_pt == pt
@pytest.mark.parametrize(
("key_data", "pad"),
itertools.product(
- (RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027,
- RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031,
- RSA_KEY_1536, RSA_KEY_2048),
+ (
+ RSA_KEY_1024,
+ RSA_KEY_1025,
+ RSA_KEY_1026,
+ RSA_KEY_1027,
+ RSA_KEY_1028,
+ RSA_KEY_1029,
+ RSA_KEY_1030,
+ RSA_KEY_1031,
+ RSA_KEY_1536,
+ RSA_KEY_2048,
+ ),
(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
- label=None
+ label=None,
),
- padding.PKCS1v15()
- )
- )
+ padding.PKCS1v15(),
+ ),
+ ),
)
def test_rsa_encrypt_key_too_small(self, key_data, pad, backend):
private_key = key_data.private_key(backend)
public_key = private_key.public_key()
# Slightly smaller than the key size but not enough for padding.
with pytest.raises(ValueError):
- public_key.encrypt(
- b"\x00" * (private_key.key_size // 8 - 1),
- pad
- )
+ public_key.encrypt(b"\x00" * (private_key.key_size // 8 - 1), pad)
# Larger than the key size.
with pytest.raises(ValueError):
- public_key.encrypt(
- b"\x00" * (private_key.key_size // 8 + 5),
- pad
- )
+ public_key.encrypt(b"\x00" * (private_key.key_size // 8 + 5), pad)
def test_unsupported_padding(self, backend):
private_key = RSA_KEY_512.private_key(backend)
@@ -1804,10 +1913,8 @@
public_key.encrypt(
b"ciphertext",
padding.OAEP(
- mgf=DummyMGF(),
- algorithm=hashes.SHA1(),
- label=None
- )
+ mgf=DummyMGF(), algorithm=hashes.SHA1(), label=None
+ ),
)
@@ -1827,7 +1934,7 @@
dmp1=1,
dmq1=1,
iqmp=2,
- public_numbers=public_numbers
+ public_numbers=public_numbers,
)
assert private_numbers.p == 3
@@ -1846,6 +1953,9 @@
public_key = RSA_KEY_1024.public_numbers.public_key(backend)
assert public_key
+ public_key = rsa.RSAPublicNumbers(n=10, e=3).public_key(backend)
+ assert public_key
+
def test_public_numbers_invalid_types(self):
with pytest.raises(TypeError):
rsa.RSAPublicNumbers(e=None, n=15)
@@ -1863,18 +1973,20 @@
(3, 5, 1, 1, None, 2, rsa.RSAPublicNumbers(e=1, n=15)),
(3, 5, 1, 1, 1, None, rsa.RSAPublicNumbers(e=1, n=15)),
(3, 5, 1, 1, 1, 2, None),
- ]
+ ],
)
- def test_private_numbers_invalid_types(self, p, q, d, dmp1, dmq1, iqmp,
- public_numbers):
+ def test_private_numbers_invalid_types(
+ self, p, q, d, dmp1, dmq1, iqmp, public_numbers
+ ):
with pytest.raises(TypeError):
rsa.RSAPrivateNumbers(
- p=p, q=q,
+ p=p,
+ q=q,
d=d,
dmp1=dmp1,
dmq1=dmq1,
iqmp=iqmp,
- public_numbers=public_numbers
+ public_numbers=public_numbers,
)
@pytest.mark.parametrize(
@@ -1884,7 +1996,7 @@
(1, 15), # public_exponent < 3
(17, 15), # public_exponent > modulus
(14, 15), # public_exponent not odd
- ]
+ ],
)
def test_invalid_public_numbers_argument_values(self, e, n, backend):
# Start with public_exponent=7, modulus=15. Then change one value at a
@@ -1909,10 +2021,11 @@
(3, 11, 3, 1, 3, 2, 6, 33), # public_exponent is not odd
(3, 11, 3, 2, 3, 2, 7, 33), # dmp1 is not odd
(3, 11, 3, 1, 4, 2, 7, 33), # dmq1 is not odd
- ]
+ ],
)
- def test_invalid_private_numbers_argument_values(self, p, q, d, dmp1, dmq1,
- iqmp, e, n, backend):
+ def test_invalid_private_numbers_argument_values(
+ self, p, q, d, dmp1, dmq1, iqmp, e, n, backend
+ ):
# Start with p=3, q=11, private_exponent=3, public_exponent=7,
# modulus=33, dmp1=1, dmq1=3, iqmp=2. Then change one value at
# a time to test the bounds.
@@ -1925,10 +2038,7 @@
dmp1=dmp1,
dmq1=dmq1,
iqmp=iqmp,
- public_numbers=rsa.RSAPublicNumbers(
- e=e,
- n=n
- )
+ public_numbers=rsa.RSAPublicNumbers(e=e, n=n),
).private_key(backend)
def test_public_number_repr(self):
@@ -2004,18 +2114,19 @@
class TestRSAPrimeFactorRecovery(object):
@pytest.mark.parametrize(
"vector",
- _flatten_pkcs1_examples(load_vectors_from_file(
- os.path.join(
- "asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"),
- load_pkcs1_vectors
- ))
+ _flatten_pkcs1_examples(
+ load_vectors_from_file(
+ os.path.join("asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"),
+ load_pkcs1_vectors,
+ )
+ ),
)
def test_recover_prime_factors(self, vector):
private, public, example = vector
p, q = rsa.rsa_recover_prime_factors(
private["modulus"],
private["public_exponent"],
- private["private_exponent"]
+ private["private_exponent"],
)
# Unfortunately there is no convention on which prime should be p
# and which one q. The function we use always makes p > q, but the
@@ -2037,22 +2148,23 @@
itertools.product(
[
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.PrivateFormat.PKCS8
+ serialization.PrivateFormat.PKCS8,
],
[
b"s",
b"longerpassword",
b"!*$&(@#$*&($T@%_somesymbols",
b"\x01" * 1000,
- ]
- )
+ ],
+ ),
)
def test_private_bytes_encrypted_pem(self, backend, fmt, password):
+ skip_fips_traditional_openssl(backend, fmt)
key = RSA_KEY_2048.private_key(backend)
serialized = key.private_bytes(
serialization.Encoding.PEM,
fmt,
- serialization.BestAvailableEncryption(password)
+ serialization.BestAvailableEncryption(password),
)
loaded_key = serialization.load_pem_private_key(
serialized, password, backend
@@ -2068,7 +2180,7 @@
(serialization.Encoding.DER, serialization.PrivateFormat.Raw),
(serialization.Encoding.Raw, serialization.PrivateFormat.Raw),
(serialization.Encoding.X962, serialization.PrivateFormat.PKCS8),
- ]
+ ],
)
def test_private_bytes_rejects_invalid(self, encoding, fmt, backend):
key = RSA_KEY_2048.private_key(backend)
@@ -2081,15 +2193,15 @@
[serialization.PrivateFormat.PKCS8, b"s"],
[serialization.PrivateFormat.PKCS8, b"longerpassword"],
[serialization.PrivateFormat.PKCS8, b"!*$&(@#$*&($T@%_somesymbol"],
- [serialization.PrivateFormat.PKCS8, b"\x01" * 1000]
- ]
+ [serialization.PrivateFormat.PKCS8, b"\x01" * 1000],
+ ],
)
def test_private_bytes_encrypted_der(self, backend, fmt, password):
key = RSA_KEY_2048.private_key(backend)
serialized = key.private_bytes(
serialization.Encoding.DER,
fmt,
- serialization.BestAvailableEncryption(password)
+ serialization.BestAvailableEncryption(password),
)
loaded_key = serialization.load_der_private_key(
serialized, password, backend
@@ -2104,27 +2216,28 @@
[
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
[
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
- ]
+ ],
)
- def test_private_bytes_unencrypted(self, backend, encoding, fmt,
- loader_func):
+ def test_private_bytes_unencrypted(
+ self, backend, encoding, fmt, loader_func
+ ):
key = RSA_KEY_2048.private_key(backend)
serialized = key.private_bytes(
encoding, fmt, serialization.NoEncryption()
@@ -2134,6 +2247,9 @@
priv_num = key.private_numbers()
assert loaded_priv_num == priv_num
+ @pytest.mark.skip_fips(
+ reason="Traditional OpenSSL key format is not supported in FIPS mode."
+ )
@pytest.mark.parametrize(
("key_path", "encoding", "loader_func"),
[
@@ -2141,17 +2257,17 @@
os.path.join(
"asymmetric",
"Traditional_OpenSSL_Serialization",
- "testrsa.pem"
+ "testrsa.pem",
),
serialization.Encoding.PEM,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
],
[
os.path.join("asymmetric", "DER_Serialization", "testrsa.der"),
serialization.Encoding.DER,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
],
- ]
+ ],
)
def test_private_bytes_traditional_openssl_unencrypted(
self, backend, key_path, encoding, loader_func
@@ -2163,7 +2279,7 @@
serialized = key.private_bytes(
encoding,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
assert serialized == key_bytes
@@ -2173,7 +2289,7 @@
key.private_bytes(
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
- serialization.BestAvailableEncryption(b"password")
+ serialization.BestAvailableEncryption(b"password"),
)
def test_private_bytes_invalid_encoding(self, backend):
@@ -2182,7 +2298,7 @@
key.private_bytes(
"notencoding",
serialization.PrivateFormat.PKCS8,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_format(self, backend):
@@ -2191,7 +2307,7 @@
key.private_bytes(
serialization.Encoding.PEM,
"invalidformat",
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_private_bytes_invalid_encryption_algorithm(self, backend):
@@ -2200,7 +2316,7 @@
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- "notanencalg"
+ "notanencalg",
)
def test_private_bytes_unsupported_encryption_type(self, backend):
@@ -2209,7 +2325,7 @@
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
- DummyKeySerializationEncryption()
+ DummyKeySerializationEncryption(),
)
@@ -2224,30 +2340,34 @@
serialization.load_pem_public_key,
serialization.Encoding.PEM,
serialization.PublicFormat.PKCS1,
- ), (
+ ),
+ (
os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.der"),
serialization.load_der_public_key,
serialization.Encoding.DER,
serialization.PublicFormat.PKCS1,
- ), (
+ ),
+ (
os.path.join("asymmetric", "PKCS8", "unenc-rsa-pkcs8.pub.pem"),
serialization.load_pem_public_key,
serialization.Encoding.PEM,
serialization.PublicFormat.SubjectPublicKeyInfo,
- ), (
+ ),
+ (
os.path.join(
"asymmetric",
"DER_Serialization",
- "unenc-rsa-pkcs8.pub.der"
+ "unenc-rsa-pkcs8.pub.der",
),
serialization.load_der_public_key,
serialization.Encoding.DER,
serialization.PublicFormat.SubjectPublicKeyInfo,
- )
- ]
+ ),
+ ],
)
- def test_public_bytes_match(self, key_path, loader_func, encoding, format,
- backend):
+ def test_public_bytes_match(
+ self, key_path, loader_func, encoding, format, backend
+ ):
key_bytes = load_vectors_from_file(
key_path, lambda pemfile: pemfile.read(), mode="rb"
)
@@ -2258,7 +2378,8 @@
def test_public_bytes_openssh(self, backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.pem"),
- lambda pemfile: pemfile.read(), mode="rb"
+ lambda pemfile: pemfile.read(),
+ mode="rb",
)
key = serialization.load_pem_public_key(key_bytes, backend)
@@ -2306,22 +2427,25 @@
[
(
serialization.Encoding.Raw,
- serialization.PublicFormat.SubjectPublicKeyInfo
+ serialization.PublicFormat.SubjectPublicKeyInfo,
),
(serialization.Encoding.Raw, serialization.PublicFormat.PKCS1),
- ] + list(itertools.product(
- [
- serialization.Encoding.Raw,
- serialization.Encoding.X962,
- serialization.Encoding.PEM,
- serialization.Encoding.DER
- ],
- [
- serialization.PublicFormat.Raw,
- serialization.PublicFormat.UncompressedPoint,
- serialization.PublicFormat.CompressedPoint
- ]
- ))
+ ]
+ + list(
+ itertools.product(
+ [
+ serialization.Encoding.Raw,
+ serialization.Encoding.X962,
+ serialization.Encoding.PEM,
+ serialization.Encoding.DER,
+ ],
+ [
+ serialization.PublicFormat.Raw,
+ serialization.PublicFormat.UncompressedPoint,
+ serialization.PublicFormat.CompressedPoint,
+ ],
+ )
+ ),
)
def test_public_bytes_rejects_invalid(self, encoding, fmt, backend):
key = RSA_KEY_2048.private_key(backend).public_key()
diff --git a/tests/hazmat/primitives/test_scrypt.py b/tests/hazmat/primitives/test_scrypt.py
index 8f3a14e..52e7e15 100644
--- a/tests/hazmat/primitives/test_scrypt.py
+++ b/tests/hazmat/primitives/test_scrypt.py
@@ -10,7 +10,9 @@
import pytest
from cryptography.exceptions import (
- AlreadyFinalized, InvalidKey, UnsupportedAlgorithm
+ AlreadyFinalized,
+ InvalidKey,
+ UnsupportedAlgorithm,
)
from cryptography.hazmat.backends.interfaces import ScryptBackend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt, _MEM_LIMIT
@@ -18,7 +20,8 @@
from tests.utils import load_nist_vectors, load_vectors_from_file
vectors = load_vectors_from_file(
- os.path.join("KDF", "scrypt.txt"), load_nist_vectors)
+ os.path.join("KDF", "scrypt.txt"), load_nist_vectors
+)
def _skip_if_memory_limited(memory_limit, params):
@@ -29,8 +32,10 @@
vlen = 32 * int(params["r"]) * (int(params["n"]) + 2) * 4
memory_required = blen + vlen
if memory_limit < memory_required:
- pytest.skip("Test exceeds Scrypt memory limit. "
- "This is likely a 32-bit platform.")
+ pytest.skip(
+ "Test exceeds Scrypt memory limit. "
+ "This is likely a 32-bit platform."
+ )
def test_memory_limit_skip():
@@ -53,8 +58,14 @@
salt = params["salt"]
derived_key = params["derived_key"]
- scrypt = Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ scrypt = Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
assert binascii.hexlify(scrypt.derive(password)) == derived_key
def test_unsupported_backend(self):
@@ -66,8 +77,14 @@
backend = object()
with pytest.raises(UnsupportedAlgorithm):
- Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
def test_salt_not_bytes(self, backend):
work_factor = 1024
@@ -77,8 +94,14 @@
salt = 1
with pytest.raises(TypeError):
- Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
def test_scrypt_malloc_failure(self, backend):
password = b"NaCl"
@@ -88,8 +111,14 @@
length = 64
salt = b"NaCl"
- scrypt = Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ scrypt = Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
with pytest.raises(MemoryError):
scrypt.derive(password)
@@ -102,8 +131,14 @@
length = 64
salt = b"NaCl"
- scrypt = Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ scrypt = Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
with pytest.raises(TypeError):
scrypt.derive(password)
@@ -116,10 +151,16 @@
length = 10
salt = b"NaCl"
- scrypt = Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ scrypt = Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
- assert scrypt.derive(password) == b'\xf4\x92\x86\xb2\x06\x0c\x848W\x87'
+ assert scrypt.derive(password) == b"\xf4\x92\x86\xb2\x06\x0c\x848W\x87"
@pytest.mark.parametrize("params", vectors)
def test_verify(self, backend, params):
@@ -132,8 +173,14 @@
salt = params["salt"]
derived_key = params["derived_key"]
- scrypt = Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ scrypt = Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
assert scrypt.verify(password, binascii.unhexlify(derived_key)) is None
def test_invalid_verify(self, backend):
@@ -145,8 +192,14 @@
salt = b"NaCl"
derived_key = b"fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e773"
- scrypt = Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ scrypt = Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
with pytest.raises(InvalidKey):
scrypt.verify(password, binascii.unhexlify(derived_key))
@@ -159,8 +212,14 @@
length = 64
salt = b"NaCl"
- scrypt = Scrypt(salt, length, work_factor, block_size,
- parallelization_factor, backend)
+ scrypt = Scrypt(
+ salt,
+ length,
+ work_factor,
+ block_size,
+ parallelization_factor,
+ backend,
+ )
scrypt.derive(password)
with pytest.raises(AlreadyFinalized):
scrypt.derive(password)
diff --git a/tests/hazmat/primitives/test_seed.py b/tests/hazmat/primitives/test_seed.py
index 29cae4f..66da978 100644
--- a/tests/hazmat/primitives/test_seed.py
+++ b/tests/hazmat/primitives/test_seed.py
@@ -24,7 +24,7 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestSEEDModeECB(object):
- test_ECB = generate_encrypt_test(
+ test_ecb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "SEED"),
["rfc-4269.txt"],
@@ -41,12 +41,12 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestSEEDModeCBC(object):
- test_CBC = generate_encrypt_test(
+ test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "SEED"),
["rfc-4196.txt"],
lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
)
@@ -58,12 +58,12 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestSEEDModeOFB(object):
- test_OFB = generate_encrypt_test(
+ test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "SEED"),
["seed-ofb.txt"],
lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)),
)
@@ -75,10 +75,10 @@
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestSEEDModeCFB(object):
- test_CFB = generate_encrypt_test(
+ test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "SEED"),
["seed-cfb.txt"],
lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))),
- lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv))
+ lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
)
diff --git a/tests/hazmat/primitives/test_serialization.py b/tests/hazmat/primitives/test_serialization.py
index 5dd7248..32debd4 100644
--- a/tests/hazmat/primitives/test_serialization.py
+++ b/tests/hazmat/primitives/test_serialization.py
@@ -11,27 +11,58 @@
import pytest
-from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
+import six
+
+from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends.interfaces import (
- DERSerializationBackend, DSABackend, EllipticCurveBackend,
- PEMSerializationBackend, RSABackend
+ DERSerializationBackend,
+ DSABackend,
+ EllipticCurveBackend,
+ PEMSerializationBackend,
+ RSABackend,
)
-from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa
+from cryptography.hazmat.primitives.asymmetric import (
+ dsa,
+ ec,
+ ed25519,
+ ed448,
+ rsa,
+ x25519,
+ x448,
+)
from cryptography.hazmat.primitives.serialization import (
- BestAvailableEncryption, Encoding, NoEncryption,
- PrivateFormat, PublicFormat,
- load_der_parameters, load_der_private_key,
- load_der_public_key, load_pem_parameters, load_pem_private_key,
- load_pem_public_key, load_ssh_public_key
+ BestAvailableEncryption,
+ Encoding,
+ NoEncryption,
+ PrivateFormat,
+ PublicFormat,
+ load_der_parameters,
+ load_der_private_key,
+ load_der_public_key,
+ load_pem_parameters,
+ load_pem_private_key,
+ load_pem_public_key,
+ load_ssh_private_key,
+ load_ssh_public_key,
+ ssh,
)
from .test_ec import _skip_curve_unsupported
from .utils import (
- _check_dsa_private_numbers, _check_rsa_private_numbers,
- load_vectors_from_file
+ _check_dsa_private_numbers,
+ _check_rsa_private_numbers,
+ load_vectors_from_file,
)
-from ...utils import raises_unsupported_algorithm
+from ...doubles import DummyKeySerializationEncryption
+
+
+def _skip_fips_format(key_path, password, backend):
+ if backend._fips_enabled:
+ if key_path[0] == "Traditional_OpenSSL_Serialization":
+ pytest.skip("Traditional OpenSSL format blocked in FIPS mode")
+ if key_path[0] == "PEM_Serialization" and password is not None:
+ pytest.skip("Encrypted PEM_Serialization blocked in FIPS mode")
class TestBufferProtocolSerialization(object):
@@ -43,12 +74,13 @@
(["DER_Serialization", "enc2-rsa-pkcs8.der"], bytearray(b"baz")),
(["DER_Serialization", "unenc-rsa-pkcs8.der"], None),
(["DER_Serialization", "testrsa.der"], None),
- ]
+ ],
)
def test_load_der_rsa_private_key(self, key_path, password, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", *key_path),
- lambda derfile: derfile.read(), mode="rb"
+ lambda derfile: derfile.read(),
+ mode="rb",
)
key = load_der_private_key(bytearray(data), password, backend)
assert key
@@ -61,21 +93,23 @@
[
(
["PEM_Serialization", "rsa_private_key.pem"],
- bytearray(b"123456")
+ bytearray(b"123456"),
),
(["PKCS8", "unenc-rsa-pkcs8.pem"], None),
(["PKCS8", "enc-rsa-pkcs8.pem"], bytearray(b"foobar")),
(["PKCS8", "enc2-rsa-pkcs8.pem"], bytearray(b"baz")),
(
["Traditional_OpenSSL_Serialization", "key1.pem"],
- bytearray(b"123456")
+ bytearray(b"123456"),
),
- ]
+ ],
)
def test_load_pem_rsa_private_key(self, key_path, password, backend):
+ _skip_fips_format(key_path, password, backend)
data = load_vectors_from_file(
os.path.join("asymmetric", *key_path),
- lambda pemfile: pemfile.read(), mode="rb"
+ lambda pemfile: pemfile.read(),
+ mode="rb",
)
key = load_pem_private_key(bytearray(data), password, backend)
assert key
@@ -93,7 +127,7 @@
(["DER_Serialization", "enc2-rsa-pkcs8.der"], b"baz"),
(["DER_Serialization", "unenc-rsa-pkcs8.der"], None),
(["DER_Serialization", "testrsa.der"], None),
- ]
+ ],
)
def test_load_der_rsa_private_key(self, key_path, password, backend):
key = load_vectors_from_file(
@@ -101,7 +135,7 @@
lambda derfile: load_der_private_key(
derfile.read(), password, backend
),
- mode="rb"
+ mode="rb",
)
assert key
assert isinstance(key, rsa.RSAPrivateKey)
@@ -115,7 +149,7 @@
(["DER_Serialization", "dsa.1024.der"], None),
(["DER_Serialization", "dsa.2048.der"], None),
(["DER_Serialization", "dsa.3072.der"], None),
- ]
+ ],
)
def test_load_der_dsa_private_key(self, key_path, password, backend):
key = load_vectors_from_file(
@@ -123,17 +157,14 @@
lambda derfile: load_der_private_key(
derfile.read(), password, backend
),
- mode="rb"
+ mode="rb",
)
assert key
assert isinstance(key, dsa.DSAPrivateKey)
_check_dsa_private_numbers(key.private_numbers())
@pytest.mark.parametrize(
- "key_path",
- [
- ["DER_Serialization", "enc-rsa-pkcs8.der"],
- ]
+ "key_path", [["DER_Serialization", "enc-rsa-pkcs8.der"]]
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_password_not_bytes(self, key_path, backend):
@@ -146,7 +177,7 @@
lambda derfile: load_der_private_key(
derfile.read(), password, backend
),
- mode="rb"
+ mode="rb",
)
@pytest.mark.parametrize(
@@ -154,7 +185,7 @@
[
(["DER_Serialization", "ec_private_key.der"], None),
(["DER_Serialization", "ec_private_key_encrypted.der"], b"123456"),
- ]
+ ],
)
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
def test_load_der_ec_private_key(self, key_path, password, backend):
@@ -164,7 +195,7 @@
lambda derfile: load_der_private_key(
derfile.read(), password, backend
),
- mode="rb"
+ mode="rb",
)
assert key
@@ -173,10 +204,7 @@
assert key.curve.key_size == 256
@pytest.mark.parametrize(
- "key_path",
- [
- ["DER_Serialization", "enc-rsa-pkcs8.der"],
- ]
+ "key_path", [["DER_Serialization", "enc-rsa-pkcs8.der"]]
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_wrong_password(self, key_path, backend):
@@ -189,14 +217,11 @@
lambda derfile: load_der_private_key(
derfile.read(), password, backend
),
- mode="rb"
+ mode="rb",
)
@pytest.mark.parametrize(
- "key_path",
- [
- ["DER_Serialization", "unenc-rsa-pkcs8.der"]
- ]
+ "key_path", [["DER_Serialization", "unenc-rsa-pkcs8.der"]]
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_unused_password(self, key_path, backend):
@@ -209,17 +234,14 @@
lambda derfile: load_der_private_key(
derfile.read(), password, backend
),
- mode="rb"
+ mode="rb",
)
@pytest.mark.parametrize(
("key_path", "password"),
itertools.product(
- [
- ["DER_Serialization", "enc-rsa-pkcs8.der"],
- ],
- [b"", None]
- )
+ [["DER_Serialization", "enc-rsa-pkcs8.der"]], [b"", None]
+ ),
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_missing_password(self, key_path, password, backend):
@@ -231,16 +253,14 @@
lambda derfile: load_der_private_key(
derfile.read(), password, backend
),
- mode="rb"
+ mode="rb",
)
def test_wrong_format(self, backend):
key_data = b"---- NOT A KEY ----\n"
with pytest.raises(ValueError):
- load_der_private_key(
- key_data, None, backend
- )
+ load_der_private_key(key_data, None, backend)
with pytest.raises(ValueError):
load_der_private_key(
@@ -249,7 +269,8 @@
def test_corrupt_der_pkcs8(self, backend):
# unenc-rsa-pkcs8 with a bunch of data missing.
- key_data = textwrap.dedent("""\
+ key_data = textwrap.dedent(
+ """\
MIICdQIBADALBgkqhkiG9w0BAQEEggJhMIICXQIBAAKBgQC7JHoJfg6yNzLMOWet
8Z49a4KD0dCspMAYvo2YAMB7/wdEycocujbhJ2n/seONi+5XqTqqFkM5VBl8rmkk
FPZk/7x0xmdsTPECSWnHK+HhoaNDFPR3j8jQhVo1laxiqcEhAHegi5cwtFosuJAv
@@ -263,13 +284,12 @@
z+KOpdpPRR5TQmbEMEspjsFpFymMiuYPgmihQbO2cJl1qScY5OkCQQCJ6m5tcN8l
Xxg/SNpjEIv+qAyUD96XVlOJlOIeLHQ8kYE0C6ZA+MsqYIzgAreJk88Yn0lU/X0/
mu/UpE/BRZmR
- """).encode()
+ """
+ ).encode()
bad_der = base64.b64decode(b"".join(key_data.splitlines()))
with pytest.raises(ValueError):
- load_der_private_key(
- bad_der, None, backend
- )
+ load_der_private_key(bad_der, None, backend)
with pytest.raises(ValueError):
load_der_private_key(
@@ -278,14 +298,16 @@
def test_corrupt_traditional_format_der(self, backend):
# privkey with a bunch of data missing.
- key_data = textwrap.dedent("""\
+ key_data = textwrap.dedent(
+ """\
MIIBPAIBAAJBAKrbeqkuRk8VcRmWFmtP+LviMB3+6dizWW3DwaffznyHGAFwUJ/I
Tv0XtbsCyl3QoyKGhrOAy3RvPK5M38iuXT0CAwEAAQJAZ3cnzaHXM/bxGaR5CR1R
rD1qFBAVfoQFiOH9uPJgMaoAuoQEisPHVcZDKcOv4wEg6/TInAIXBnEigtqvRzuy
mvcpHZwQJdmdHHkGKAs37Dfxi67HbkUCIQCeZGliHXFa071Fp06ZeWlR2ADonTZz
rJBhdTe0v5pCeQIhAIZfkiGgGBX4cIuuckzEm43g9WMUjxP/0GlK39vIyihxAiEA
mymehFRT0MvqW5xAKAx7Pgkt8HVKwVhc2LwGKHE0DZM=
- """).encode()
+ """
+ ).encode()
bad_der = base64.b64decode(b"".join(key_data.splitlines()))
with pytest.raises(ValueError):
@@ -300,20 +322,20 @@
"key_file",
[
os.path.join(
- "asymmetric", "DER_Serialization", "unenc-rsa-pkcs8.pub.der"),
+ "asymmetric", "DER_Serialization", "unenc-rsa-pkcs8.pub.der"
+ ),
os.path.join(
- "asymmetric", "DER_Serialization", "rsa_public_key.der"),
+ "asymmetric", "DER_Serialization", "rsa_public_key.der"
+ ),
os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.der"),
- ]
+ ],
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_load_der_rsa_public_key(self, key_file, backend):
key = load_vectors_from_file(
key_file,
- lambda derfile: load_der_public_key(
- derfile.read(), backend
- ),
- mode="rb"
+ lambda derfile: load_der_public_key(derfile.read(), backend),
+ mode="rb",
)
assert key
assert isinstance(key, rsa.RSAPublicKey)
@@ -328,19 +350,19 @@
"key_file",
[
os.path.join(
- "asymmetric", "DER_Serialization", "unenc-dsa-pkcs8.pub.der"),
+ "asymmetric", "DER_Serialization", "unenc-dsa-pkcs8.pub.der"
+ ),
os.path.join(
- "asymmetric", "DER_Serialization", "dsa_public_key.der"),
- ]
+ "asymmetric", "DER_Serialization", "dsa_public_key.der"
+ ),
+ ],
)
@pytest.mark.requires_backend_interface(interface=DSABackend)
def test_load_der_dsa_public_key(self, key_file, backend):
key = load_vectors_from_file(
key_file,
- lambda derfile: load_der_public_key(
- derfile.read(), backend
- ),
- mode="rb"
+ lambda derfile: load_der_public_key(derfile.read(), backend),
+ mode="rb",
)
assert key
assert isinstance(key, dsa.DSAPublicKey)
@@ -350,12 +372,10 @@
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
- "asymmetric", "DER_Serialization",
- "ec_public_key.der"),
- lambda derfile: load_der_public_key(
- derfile.read(), backend
+ "asymmetric", "DER_Serialization", "ec_public_key.der"
),
- mode="rb"
+ lambda derfile: load_der_public_key(derfile.read(), backend),
+ mode="rb",
)
assert key
assert isinstance(key, ec.EllipticCurvePublicKey)
@@ -366,9 +386,7 @@
param_data = b"---- NOT A KEY ----\n"
with pytest.raises(ValueError):
- load_der_parameters(
- param_data, backend
- )
+ load_der_parameters(param_data, backend)
@pytest.mark.requires_backend_interface(interface=PEMSerializationBackend)
@@ -393,16 +411,19 @@
(["Traditional_OpenSSL_Serialization", "key1.pem"], b"123456"),
(["Traditional_OpenSSL_Serialization", "key2.pem"], b"a123456"),
(["Traditional_OpenSSL_Serialization", "testrsa.pem"], None),
- (["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"],
- b"password"),
- ]
+ (
+ ["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"],
+ b"password",
+ ),
+ ],
)
def test_load_pem_rsa_private_key(self, key_file, password, backend):
+ _skip_fips_format(key_file, password, backend)
key = load_vectors_from_file(
os.path.join("asymmetric", *key_file),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
assert key
@@ -417,14 +438,15 @@
(["Traditional_OpenSSL_Serialization", "dsa.3072.pem"], None),
(["PKCS8", "unenc-dsa-pkcs8.pem"], None),
(["PEM_Serialization", "dsa_private_key.pem"], b"123456"),
- ]
+ ],
)
def test_load_dsa_private_key(self, key_path, password, backend):
+ _skip_fips_format(key_path, password, backend)
key = load_vectors_from_file(
os.path.join("asymmetric", *key_path),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
assert key
assert isinstance(key, dsa.DSAPrivateKey)
@@ -437,16 +459,17 @@
(["PKCS8", "ec_private_key_encrypted.pem"], b"123456"),
(["PEM_Serialization", "ec_private_key.pem"], None),
(["PEM_Serialization", "ec_private_key_encrypted.pem"], b"123456"),
- ]
+ ],
)
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
def test_load_pem_ec_private_key(self, key_path, password, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
+ _skip_fips_format(key_path, password, backend)
key = load_vectors_from_file(
os.path.join("asymmetric", *key_path),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
assert key
@@ -459,16 +482,17 @@
[
os.path.join("asymmetric", "PKCS8", "unenc-rsa-pkcs8.pub.pem"),
os.path.join(
- "asymmetric", "PEM_Serialization", "rsa_public_key.pem"),
+ "asymmetric", "PEM_Serialization", "rsa_public_key.pem"
+ ),
os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.pem"),
- ]
+ ],
)
def test_load_pem_rsa_public_key(self, key_file, backend):
key = load_vectors_from_file(
key_file,
lambda pemfile: load_pem_public_key(
pemfile.read().encode(), backend
- )
+ ),
)
assert key
assert isinstance(key, rsa.RSAPublicKey)
@@ -480,16 +504,16 @@
[
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pub.pem"),
os.path.join(
- "asymmetric", "PEM_Serialization",
- "dsa_public_key.pem"),
- ]
+ "asymmetric", "PEM_Serialization", "dsa_public_key.pem"
+ ),
+ ],
)
def test_load_pem_dsa_public_key(self, key_file, backend):
key = load_vectors_from_file(
key_file,
lambda pemfile: load_pem_public_key(
pemfile.read().encode(), backend
- )
+ ),
)
assert key
assert isinstance(key, dsa.DSAPublicKey)
@@ -499,66 +523,70 @@
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
- "asymmetric", "PEM_Serialization",
- "ec_public_key.pem"),
+ "asymmetric", "PEM_Serialization", "ec_public_key.pem"
+ ),
lambda pemfile: load_pem_public_key(
pemfile.read().encode(), backend
- )
+ ),
)
assert key
assert isinstance(key, ec.EllipticCurvePublicKey)
assert key.curve.name == "secp256r1"
assert key.curve.key_size == 256
+ @pytest.mark.skip_fips(
+ reason="Traditional OpenSSL format blocked in FIPS mode"
+ )
def test_rsa_traditional_encrypted_values(self, backend):
pkey = load_vectors_from_file(
os.path.join(
- "asymmetric", "Traditional_OpenSSL_Serialization", "key1.pem"),
+ "asymmetric", "Traditional_OpenSSL_Serialization", "key1.pem"
+ ),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), b"123456", backend
- )
+ ),
)
assert pkey
numbers = pkey.private_numbers()
assert numbers.p == int(
"fb7d316fc51531b36d93adaefaf52db6ad5beb793d37c4cf9dfc1ddd17cfbafb",
- 16
+ 16,
)
assert numbers.q == int(
"df98264e646de9a0fbeab094e31caad5bc7adceaaae3c800ca0275dd4bb307f5",
- 16
+ 16,
)
assert numbers.d == int(
"db4848c36f478dd5d38f35ae519643b6b810d404bcb76c00e44015e56ca1cab0"
"7bb7ae91f6b4b43fcfc82a47d7ed55b8c575152116994c2ce5325ec24313b911",
- 16
+ 16,
)
assert numbers.dmp1 == int(
"ce997f967192c2bcc3853186f1559fd355c190c58ddc15cbf5de9b6df954c727",
- 16
+ 16,
)
assert numbers.dmq1 == int(
"b018a57ab20ffaa3862435445d863369b852cf70a67c55058213e3fe10e3848d",
- 16
+ 16,
)
assert numbers.iqmp == int(
"6a8d830616924f5cf2d1bc1973f97fde6b63e052222ac7be06aa2532d10bac76",
- 16
+ 16,
)
assert numbers.public_numbers.e == 65537
assert numbers.public_numbers.n == int(
"dba786074f2f0350ce1d99f5aed5b520cfe0deb5429ec8f2a88563763f566e77"
"9814b7c310e5326edae31198eed439b845dd2db99eaa60f5c16a43f4be6bcf37",
- 16
+ 16,
)
@pytest.mark.parametrize(
"key_path",
[
["Traditional_OpenSSL_Serialization", "testrsa.pem"],
- ["PKCS8", "unenc-rsa-pkcs8.pem"]
- ]
+ ["PKCS8", "unenc-rsa-pkcs8.pem"],
+ ],
)
def test_unused_password(self, key_path, backend):
key_file = os.path.join("asymmetric", *key_path)
@@ -569,15 +597,33 @@
key_file,
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
+ def test_invalid_encoding_with_traditional(self, backend):
+ key_file = os.path.join(
+ "asymmetric", "Traditional_OpenSSL_Serialization", "testrsa.pem"
+ )
+ key = load_vectors_from_file(
+ key_file,
+ lambda pemfile: load_pem_private_key(
+ pemfile.read(), None, backend
+ ),
+ mode="rb",
+ )
+
+ for enc in (Encoding.OpenSSH, Encoding.Raw, Encoding.X962):
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ enc, PrivateFormat.TraditionalOpenSSL, NoEncryption()
+ )
+
@pytest.mark.parametrize(
"key_path",
[
["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"],
- ["PKCS8", "enc-rsa-pkcs8.pem"]
- ]
+ ["PKCS8", "enc-rsa-pkcs8.pem"],
+ ],
)
def test_password_not_bytes(self, key_path, backend):
key_file = os.path.join("asymmetric", *key_path)
@@ -588,15 +634,15 @@
key_file,
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
@pytest.mark.parametrize(
"key_path",
[
["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"],
- ["PKCS8", "enc-rsa-pkcs8.pem"]
- ]
+ ["PKCS8", "enc-rsa-pkcs8.pem"],
+ ],
)
def test_wrong_password(self, key_path, backend):
key_file = os.path.join("asymmetric", *key_path)
@@ -607,19 +653,18 @@
key_file,
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
@pytest.mark.parametrize(
("key_path", "password"),
itertools.product(
[
- ["Traditional_OpenSSL_Serialization",
- "testrsa-encrypted.pem"],
+ ["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"],
["PKCS8", "enc-rsa-pkcs8.pem"],
],
- [b"", None]
- )
+ [b"", None],
+ ),
)
def test_missing_password(self, key_path, password, backend):
key_file = os.path.join("asymmetric", *key_path)
@@ -629,16 +674,14 @@
key_file,
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
def test_wrong_private_format(self, backend):
key_data = b"---- NOT A KEY ----\n"
with pytest.raises(ValueError):
- load_pem_private_key(
- key_data, None, backend
- )
+ load_pem_private_key(key_data, None, backend)
with pytest.raises(ValueError):
load_pem_private_key(
@@ -659,7 +702,8 @@
def test_corrupt_traditional_format(self, backend):
# privkey.pem with a bunch of data missing.
- key_data = textwrap.dedent("""\
+ key_data = textwrap.dedent(
+ """\
-----BEGIN RSA PRIVATE KEY-----
MIIBPAIBAAJBAKrbeqkuRk8VcRmWFmtP+LviMB3+6dizWW3DwaffznyHGAFwUJ/I
Tv0XtbsCyl3QoyKGhrOAy3RvPK5M38iuXT0CAwEAAQJAZ3cnzaHXM/bxGaR5CR1R
@@ -668,12 +712,11 @@
rJBhdTe0v5pCeQIhAIZfkiGgGBX4cIuuckzEm43g9WMUjxP/0GlK39vIyihxAiEA
mymehFRT0MvqW5xAKAx7Pgkt8HVKwVhc2LwGKHE0DZM=
-----END RSA PRIVATE KEY-----
- """).encode()
+ """
+ ).encode()
with pytest.raises(ValueError):
- load_pem_private_key(
- key_data, None, backend
- )
+ load_pem_private_key(key_data, None, backend)
with pytest.raises(ValueError):
load_pem_private_key(
@@ -682,7 +725,8 @@
def test_traditional_encrypted_corrupt_format(self, backend):
# privkey.pem with a single bit flipped
- key_data = textwrap.dedent("""\
+ key_data = textwrap.dedent(
+ """\
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: <,ENCRYPTED
DEK-Info: AES-128-CBC,5E22A2BD85A653FB7A3ED20DE84F54CD
@@ -695,22 +739,20 @@
5A295jD9BQp9CY0nNFSsy+qiXWToq2xT3y5zVNEStmN0SCGNaIlUnJzL9IHW+oMI
kPmXZMnAYBWeeCF1gf3J3aE5lZInegHNfEI0+J0LazC2aNU5Dg/BNqrmRqKWEIo/
-----END RSA PRIVATE KEY-----
- """).encode()
+ """
+ ).encode()
password = b"this password is wrong"
with pytest.raises(ValueError):
- load_pem_private_key(
- key_data, None, backend
- )
+ load_pem_private_key(key_data, None, backend)
with pytest.raises(ValueError):
- load_pem_private_key(
- key_data, password, backend
- )
+ load_pem_private_key(key_data, password, backend)
def test_unsupported_key_encryption(self, backend):
- key_data = textwrap.dedent("""\
+ key_data = textwrap.dedent(
+ """\
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: FAKE-123,5E22A2BD85A653FB7A3ED20DE84F54CD
@@ -723,18 +765,18 @@
5A295jD9BQp9CY0nNFSsy+qiXWToq2xT3y5zVNEStmN0SCGNaIlUnJzL9IHW+oMI
kPmXZMnAYBWeeCF1gf3J3aE5lZInegHNfEI0+J0LazC2aNU5Dg/BNqrmRqKWEIo/
-----END RSA PRIVATE KEY-----
- """).encode()
+ """
+ ).encode()
password = b"password"
- with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
- load_pem_private_key(
- key_data, password, backend
- )
+ with pytest.raises(ValueError):
+ load_pem_private_key(key_data, password, backend)
def test_corrupt_pkcs8_format(self, backend):
# unenc-rsa-pkcs8.pem with a bunch of data missing.
- key_data = textwrap.dedent("""\
+ key_data = textwrap.dedent(
+ """\
-----BEGIN PRIVATE KEY-----
MIICdQIBADALBgkqhkiG9w0BAQEEggJhMIICXQIBAAKBgQC7JHoJfg6yNzLMOWet
8Z49a4KD0dCspMAYvo2YAMB7/wdEycocujbhJ2n/seONi+5XqTqqFkM5VBl8rmkk
@@ -750,12 +792,11 @@
Xxg/SNpjEIv+qAyUD96XVlOJlOIeLHQ8kYE0C6ZA+MsqYIzgAreJk88Yn0lU/X0/
mu/UpE/BRZmR
-----END PRIVATE KEY-----
- """).encode()
+ """
+ ).encode()
with pytest.raises(ValueError):
- load_pem_private_key(
- key_data, None, backend
- )
+ load_pem_private_key(key_data, None, backend)
with pytest.raises(ValueError):
load_pem_private_key(
@@ -764,7 +805,8 @@
def test_pks8_encrypted_corrupt_format(self, backend):
# enc-rsa-pkcs8.pem with some bits flipped.
- key_data = textwrap.dedent("""\
+ key_data = textwrap.dedent(
+ """\
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICojAcBgoqhkiG9w0BDAEDMA4ECHK0M0+QuEL9AgIBIcSCAoDRq+KRY+0XP0tO
lwBTzViiXSXoyNnKAZKt5r5K/fGNntv22g/1s/ZNCetrqsJDC5eMUPPacz06jFq/
@@ -782,27 +824,23 @@
6JLgl8FrvdfjHwIvmSOO1YMNmILBq000Q8WDqyErBDs4hsvtO6VQ4LeqJj6gClX3
qeJNaJFu
-----END ENCRYPTED PRIVATE KEY-----
- """).encode()
+ """
+ ).encode()
password = b"this password is wrong"
with pytest.raises(ValueError):
- load_pem_private_key(
- key_data, None, backend
- )
+ load_pem_private_key(key_data, None, backend)
with pytest.raises(ValueError):
- load_pem_private_key(
- key_data, password, backend
- )
+ load_pem_private_key(key_data, password, backend)
def test_rsa_pkcs8_encrypted_values(self, backend):
pkey = load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", "enc-rsa-pkcs8.pem"),
+ os.path.join("asymmetric", "PKCS8", "enc-rsa-pkcs8.pem"),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), b"foobar", backend
- )
+ ),
)
assert pkey
@@ -813,7 +851,8 @@
"376a7fe5b19f95b35ca358ea5c8abd7ae051d49cd2f1e45969a1ae945460"
"3c14b278664a0e414ebc8913acb6203626985525e17a600611b028542dd0"
"562aad787fb4f1650aa318cdcff751e1b187cbf6785fbe164e9809491b95"
- "dd68480567c99b1a57", 16
+ "dd68480567c99b1a57",
+ 16,
)
assert numbers.public_numbers.e == 65537
@@ -823,37 +862,43 @@
"f3d9785c3a2c09e4c8090909fb3721e19a3009ec21221523a729265707a5"
"8f13063671c42a4096cad378ef2510cb59e23071489d8893ac4934dd149f"
"34f2d094bea57f1c8027c3a77248ac9b91218737d0c3c3dfa7d7829e6977"
- "cf7d995688c86c81", 16
+ "cf7d995688c86c81",
+ 16,
)
assert numbers.p == int(
"00db122ac857b2c0437d7616daa98e597bb75ca9ad3a47a70bec10c10036"
"03328794b225c8e3eee6ffd3fd6d2253d28e071fe27d629ab072faa14377"
- "ce6118cb67", 16
+ "ce6118cb67",
+ 16,
)
assert numbers.q == int(
"00df1b8aa8506fcbbbb9d00257f2975e38b33d2698fd0f37e82d7ef38c56"
"f21b6ced63c825383782a7115cfcc093300987dbd2853b518d1c8f26382a"
- "2d2586d391", 16
+ "2d2586d391",
+ 16,
)
assert numbers.dmp1 == int(
"00be18aca13e60712fdf5daa85421eb10d86d654b269e1255656194fb0c4"
"2dd01a1070ea12c19f5c39e09587af02f7b1a1030d016a9ffabf3b36d699"
- "ceaf38d9bf", 16
+ "ceaf38d9bf",
+ 16,
)
assert numbers.dmq1 == int(
"71aa8978f90a0c050744b77cf1263725b203ac9f730606d8ae1d289dce4a"
"28b8d534e9ea347aeb808c73107e583eb80c546d2bddadcdb3c82693a4c1"
- "3d863451", 16
+ "3d863451",
+ 16,
)
assert numbers.iqmp == int(
"136b7b1afac6e6279f71b24217b7083485a5e827d156024609dae39d48a6"
"bdb55af2f062cc4a3b077434e6fffad5faa29a2b5dba2bed3e4621e478c0"
- "97ccfe7f", 16
+ "97ccfe7f",
+ 16,
)
def test_load_pem_dsa_private_key(self, backend):
@@ -861,7 +906,7 @@
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), None, backend
- )
+ ),
)
assert key
assert isinstance(key, dsa.DSAPrivateKey)
@@ -872,15 +917,14 @@
num = key.private_numbers()
pub = num.public_numbers
parameter_numbers = pub.parameter_numbers
- assert num.x == int("00a535a8e1d0d91beafc8bee1d9b2a3a8de3311203",
- 16)
+ assert num.x == int("00a535a8e1d0d91beafc8bee1d9b2a3a8de3311203", 16)
assert pub.y == int(
"2b260ea97dc6a12ae932c640e7df3d8ff04a8a05a0324f8d5f1b23f15fa1"
"70ff3f42061124eff2586cb11b49a82dcdc1b90fc6a84fb10109cb67db5d"
"2da971aeaf17be5e37284563e4c64d9e5fc8480258b319f0de29d54d8350"
"70d9e287914d77df81491f4423b62da984eb3f45eb2a29fcea5dae525ac6"
"ab6bcce04bfdf5b6",
- 16
+ 16,
)
assert parameter_numbers.p == int(
@@ -889,11 +933,12 @@
"071d4dceb2782794ad393cc08a4d4ada7f68d6e839a5fcd34b4e402d82cb"
"8a8cb40fec31911bf9bd360b034caacb4c5e947992573c9e90099c1b0f05"
"940cabe5d2de49a167",
- 16
+ 16,
)
assert parameter_numbers.q == int(
- "00adc0e869b36f0ac013a681fdf4d4899d69820451", 16)
+ "00adc0e869b36f0ac013a681fdf4d4899d69820451", 16
+ )
assert parameter_numbers.g == int(
"008c6b4589afa53a4d1048bfc346d1f386ca75521ccf72ddaa251286880e"
@@ -901,69 +946,61 @@
"e71141ba324f5b93131929182c88a9fa4062836066cebe74b5c6690c7d10"
"1106c240ab7ebd54e4e3301fd086ce6adac922fb2713a2b0887cba13b9bc"
"68ce5cfff241cd3246",
- 16
+ 16,
)
@pytest.mark.parametrize(
- ("key_file", "password"),
- [
- ("bad-oid-dsa-key.pem", None),
- ]
+ ("key_file", "password"), [("bad-oid-dsa-key.pem", None)]
)
def test_load_bad_oid_key(self, key_file, password, backend):
with pytest.raises(ValueError):
load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", key_file),
+ os.path.join("asymmetric", "PKCS8", key_file),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
@pytest.mark.parametrize(
- ("key_file", "password"),
- [
- ("bad-encryption-oid.pem", b"password"),
- ]
+ ("key_file", "password"), [("bad-encryption-oid.pem", b"password")]
)
def test_load_bad_encryption_oid_key(self, key_file, password, backend):
- with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
+ with pytest.raises(ValueError):
load_vectors_from_file(
- os.path.join(
- "asymmetric", "PKCS8", key_file),
+ os.path.join("asymmetric", "PKCS8", key_file),
lambda pemfile: load_pem_private_key(
pemfile.read().encode(), password, backend
- )
+ ),
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSASSHSerialization(object):
def test_load_ssh_public_key_unsupported(self, backend):
- ssh_key = b'ecdsa-sha2-junk AAAAE2VjZHNhLXNoYTItbmlzdHAyNTY='
+ ssh_key = b"ecdsa-sha2-junk AAAAE2VjZHNhLXNoYTItbmlzdHAyNTY="
with pytest.raises(UnsupportedAlgorithm):
load_ssh_public_key(ssh_key, backend)
def test_load_ssh_public_key_bad_format(self, backend):
- ssh_key = b'ssh-rsa not-a-real-key'
+ ssh_key = b"ssh-rsa not-a-real-key"
with pytest.raises(ValueError):
load_ssh_public_key(ssh_key, backend)
def test_load_ssh_public_key_rsa_too_short(self, backend):
- ssh_key = b'ssh-rsa'
+ ssh_key = b"ssh-rsa"
with pytest.raises(ValueError):
load_ssh_public_key(ssh_key, backend)
def test_load_ssh_public_key_truncated_int(self, backend):
- ssh_key = b'ssh-rsa AAAAB3NzaC1yc2EAAAA='
+ ssh_key = b"ssh-rsa AAAAB3NzaC1yc2EAAAA="
with pytest.raises(ValueError):
load_ssh_public_key(ssh_key, backend)
- ssh_key = b'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAACKr+IHXo'
+ ssh_key = b"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAACKr+IHXo"
with pytest.raises(ValueError):
load_ssh_public_key(ssh_key, backend)
@@ -1032,16 +1069,18 @@
expected_e = 0x10001
expected_n = int(
- '00C3BBF5D13F59322BA0A0B77EA0B6CF570241628AE24B5BA454D'
- '23DCA295652B3523B67752653DFFD69587FAD9578DD6406F23691'
- 'EA491C3F8B2D391D0312D9653C303B651067ADF887A5241843CEF'
- '8019680A088E092FEC305FB04EA070340BB9BD0F1635B2AD84142'
- '61B4E2D010ABD8FC6D2FB768912F78EE6B05A60857532B75B75EF'
- 'C007601A4EF58BA947B7E75E38F3443CDD87E7C138A1DAD9D9FB3'
- '19FF69DA43A9F6F6B0CD243F042CD1A5AFAEB286BD46AEB2D922B'
- 'D01385D6892167074A0907F94A2BF08A54ABB2FFFFC89920861D0'
- '46F8706AB88DDADBD9E8204D48B87789081E074024C8996783B31'
- '7076A98ABF0A2D8550EAF2097D8CCC7BE76EF', 16)
+ "00C3BBF5D13F59322BA0A0B77EA0B6CF570241628AE24B5BA454D"
+ "23DCA295652B3523B67752653DFFD69587FAD9578DD6406F23691"
+ "EA491C3F8B2D391D0312D9653C303B651067ADF887A5241843CEF"
+ "8019680A088E092FEC305FB04EA070340BB9BD0F1635B2AD84142"
+ "61B4E2D010ABD8FC6D2FB768912F78EE6B05A60857532B75B75EF"
+ "C007601A4EF58BA947B7E75E38F3443CDD87E7C138A1DAD9D9FB3"
+ "19FF69DA43A9F6F6B0CD243F042CD1A5AFAEB286BD46AEB2D922B"
+ "D01385D6892167074A0907F94A2BF08A54ABB2FFFFC89920861D0"
+ "46F8706AB88DDADBD9E8204D48B87789081E074024C8996783B31"
+ "7076A98ABF0A2D8550EAF2097D8CCC7BE76EF",
+ 16,
+ )
expected = rsa.RSAPublicNumbers(expected_e, expected_n)
@@ -1051,7 +1090,7 @@
@pytest.mark.requires_backend_interface(interface=DSABackend)
class TestDSSSSHSerialization(object):
def test_load_ssh_public_key_dss_too_short(self, backend):
- ssh_key = b'ssh-dss'
+ ssh_key = b"ssh-dss"
with pytest.raises(ValueError):
load_ssh_public_key(ssh_key, backend)
@@ -1134,14 +1173,16 @@
"96a7032c01cdd8485b5cbfb73a46bb04708f98a18bc88d4c7812b284da8f900"
"6e473e89897f9bc9125c69bbfd8ef691c0e76c1c34e6c843b8fe240e6e5aeb3"
"13486e5fa917ab1288ff1a6ebcf9dcdeed3c5fc88474e30476f53a5ec816ef6"
- "9f4", 16
+ "9f4",
+ 16,
)
expected_p = int(
"b9b052d7f07630148d4d838b17790ef4f43437238ebebd5032ea483fd7b7902"
"5ec3dc65ebd563ab586a633b4344f6acd10af31353bcf29111fa5e3b8d5c1e8"
"7befe3c65f9b8be69c740716698c8366c8ef925b9cec1dcd69e73d926b554e2"
"b4b6ddd1453eab39ba0f846e1555adcc33c5a8637128c9ed61104a45505a748"
- "f6db", 16
+ "f6db",
+ 16,
)
expected_q = 1230879958723280233885494314531920096931919647917
expected_g = int(
@@ -1149,11 +1190,12 @@
"7bc249b6cf8f5f5c5022afefd4df5bf9d13bbdf182df5af2a5c5d1dc7604185"
"7d5b0e4b22b856c300f850a3b00bac394b728755b8b7a56522eefc491573967"
"debb5982fc94d6a8c291f758feae63ad769a5621947221522a2dc31d18ede6f"
- "b656", 16
+ "b656",
+ 16,
)
expected = dsa.DSAPublicNumbers(
expected_y,
- dsa.DSAParameterNumbers(expected_p, expected_q, expected_g)
+ dsa.DSAParameterNumbers(expected_p, expected_q, expected_g),
)
assert numbers == expected
@@ -1174,17 +1216,32 @@
expected_x = int(
"44196257377740326295529888716212621920056478823906609851236662550"
- "785814128027", 10
+ "785814128027",
+ 10,
)
expected_y = int(
"12257763433170736656417248739355923610241609728032203358057767672"
- "925775019611", 10
+ "925775019611",
+ 10,
)
assert key.public_numbers() == ec.EllipticCurvePublicNumbers(
expected_x, expected_y, ec.SECP256R1()
)
+ def test_load_ssh_public_key_byteslike(self, backend):
+ _skip_curve_unsupported(backend, ec.SECP256R1())
+
+ ssh_key = (
+ b"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAy"
+ b"NTYAAABBBGG2MfkHXp0UkxUyllDzWNBAImsvt5t7pFtTXegZK2WbGxml8zMrgWi5"
+ b"teIg1TO03/FD9hbpBFgBeix3NrCFPls= root@cloud-server-01"
+ )
+ assert load_ssh_public_key(bytearray(ssh_key), backend)
+ if six.PY3:
+ assert load_ssh_public_key(memoryview(ssh_key), backend)
+ assert load_ssh_public_key(memoryview(bytearray(ssh_key)), backend)
+
def test_load_ssh_public_key_ecdsa_nist_p384(self, backend):
_skip_curve_unsupported(backend, ec.SECP384R1())
ssh_key = (
@@ -1197,11 +1254,13 @@
expected_x = int(
"31541830871345183397582554827482786756220448716666815789487537666"
- "592636882822352575507883817901562613492450642523901", 10
+ "592636882822352575507883817901562613492450642523901",
+ 10,
)
expected_y = int(
"15111413269431823234030344298767984698884955023183354737123929430"
- "995703524272335782455051101616329050844273733614670", 10
+ "995703524272335782455051101616329050844273733614670",
+ 10,
)
assert key.public_numbers() == ec.EllipticCurvePublicNumbers(
@@ -1222,12 +1281,14 @@
expected_x = int(
"54124123120178189598842622575230904027376313369742467279346415219"
"77809037378785192537810367028427387173980786968395921877911964629"
- "142163122798974160187785455", 10
+ "142163122798974160187785455",
+ 10,
)
expected_y = int(
"16111775122845033200938694062381820957441843014849125660011303579"
"15284560361402515564433711416776946492019498546572162801954089916"
- "006665939539407104638103918", 10
+ "006665939539407104638103918",
+ 10,
)
assert key.public_numbers() == ec.EllipticCurvePublicNumbers(
@@ -1274,6 +1335,51 @@
load_ssh_public_key(ssh_key, backend)
+@pytest.mark.supported(
+ only_if=lambda backend: backend.ed25519_supported(),
+ skip_message="Requires OpenSSL with Ed25519 support",
+)
+class TestEd25519SSHSerialization(object):
+ def test_load_ssh_public_key(self, backend):
+ ssh_key = (
+ b"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2fgpmpYO61qeAxGd0wgRaN/E4"
+ b"GR+xWvBmvxjxrB1vG user@chiron.local"
+ )
+ key = load_ssh_public_key(ssh_key, backend)
+ assert isinstance(key, ed25519.Ed25519PublicKey)
+ assert key.public_bytes(Encoding.Raw, PublicFormat.Raw) == (
+ b"m\x9f\x82\x99\xa9`\xee\xb5\xa9\xe01\x19\xdd0\x81\x16\x8d\xfc"
+ b"N\x06G\xecV\xbc\x19\xaf\xc6<k\x07[\xc6"
+ )
+
+ def test_public_bytes_openssh(self, backend):
+ ssh_key = (
+ b"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2fgpmpYO61qeAxGd0wgRaN/E4"
+ b"GR+xWvBmvxjxrB1vG"
+ )
+ key = load_ssh_public_key(ssh_key, backend)
+ assert isinstance(key, ed25519.Ed25519PublicKey)
+ assert (
+ key.public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH) == ssh_key
+ )
+
+ def test_load_ssh_public_key_not_32_bytes(self, backend):
+ ssh_key = (
+ b"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI22fgpmpYO61qeAxGd0wgRaN/E4"
+ b"GR+xWvBmvxjxrB1vGaGVs user@chiron.local"
+ )
+ with pytest.raises(ValueError):
+ load_ssh_public_key(ssh_key, backend)
+
+ def test_load_ssh_public_key_trailing_data(self, backend):
+ ssh_key = (
+ b"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2fgpmpYO61qeAxGd0wgRa"
+ b"N/E4GR+xWvBmvxjxrB1vGdHJhaWxpbmdkYXRh user@chiron.local"
+ )
+ with pytest.raises(ValueError):
+ load_ssh_public_key(ssh_key, backend)
+
+
class TestKeySerializationEncryptionTypes(object):
def test_non_bytes_password(self):
with pytest.raises(ValueError):
@@ -1285,128 +1391,959 @@
@pytest.mark.supported(
+ only_if=lambda backend: backend.ed25519_supported(),
+ skip_message="Requires OpenSSL with Ed25519 support",
+)
+class TestEd25519Serialization(object):
+ def test_load_der_private_key(self, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8-enc.der"),
+ lambda derfile: derfile.read(),
+ mode="rb",
+ )
+ unencrypted = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8.der"),
+ lambda derfile: derfile.read(),
+ mode="rb",
+ )
+ key = load_der_private_key(data, b"password", backend)
+ assert (
+ key.private_bytes(
+ Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
+
+ def test_load_pem_private_key(self, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8-enc.pem"),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ unencrypted = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8.pem"),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ key = load_pem_private_key(data, b"password", backend)
+ assert (
+ key.private_bytes(
+ Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
+
+ @pytest.mark.parametrize(
+ ("key_path", "encoding", "loader"),
+ [
+ (
+ ["Ed25519", "ed25519-pub.pem"],
+ Encoding.PEM,
+ load_pem_public_key,
+ ),
+ (
+ ["Ed25519", "ed25519-pub.der"],
+ Encoding.DER,
+ load_der_public_key,
+ ),
+ ],
+ )
+ def test_load_public_key(self, key_path, encoding, loader, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", *key_path),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ public_key = loader(data, backend)
+ assert (
+ public_key.public_bytes(
+ encoding, PublicFormat.SubjectPublicKeyInfo
+ )
+ == data
+ )
+
+ def test_openssl_serialization_unsupported(self, backend):
+ key = ed25519.Ed25519PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.DER,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+
+
+@pytest.mark.supported(
only_if=lambda backend: backend.x448_supported(),
- skip_message="Requires OpenSSL with X448 support"
+ skip_message="Requires OpenSSL with X448 support",
)
class TestX448Serialization(object):
def test_load_der_private_key(self, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8-enc.der"),
lambda derfile: derfile.read(),
- mode="rb"
+ mode="rb",
)
unencrypted = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8.der"),
lambda derfile: derfile.read(),
- mode="rb"
+ mode="rb",
)
key = load_der_private_key(data, b"password", backend)
- assert key.private_bytes(
- Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
- ) == unencrypted
+ assert (
+ key.private_bytes(
+ Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
def test_load_pem_private_key(self, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8-enc.pem"),
lambda pemfile: pemfile.read(),
- mode="rb"
+ mode="rb",
)
unencrypted = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8.pem"),
lambda pemfile: pemfile.read(),
- mode="rb"
+ mode="rb",
)
key = load_pem_private_key(data, b"password", backend)
- assert key.private_bytes(
- Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
- ) == unencrypted
+ assert (
+ key.private_bytes(
+ Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
@pytest.mark.parametrize(
("key_path", "encoding", "loader"),
[
- (
- ["X448", "x448-pub.pem"],
- Encoding.PEM,
- load_pem_public_key
- ),
- (
- ["X448", "x448-pub.der"],
- Encoding.DER,
- load_der_public_key
- ),
- ]
+ (["X448", "x448-pub.pem"], Encoding.PEM, load_pem_public_key),
+ (["X448", "x448-pub.der"], Encoding.DER, load_der_public_key),
+ ],
)
def test_load_public_key(self, key_path, encoding, loader, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", *key_path),
lambda pemfile: pemfile.read(),
- mode="rb"
+ mode="rb",
)
public_key = loader(data, backend)
- assert public_key.public_bytes(
- encoding, PublicFormat.SubjectPublicKeyInfo
- ) == data
+ assert (
+ public_key.public_bytes(
+ encoding, PublicFormat.SubjectPublicKeyInfo
+ )
+ == data
+ )
+
+ def test_openssl_serialization_unsupported(self, backend):
+ key = x448.X448PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.DER,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+
+ def test_openssh_serialization_unsupported(self, backend):
+ key = x448.X448PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM, PrivateFormat.OpenSSH, NoEncryption()
+ )
@pytest.mark.supported(
only_if=lambda backend: backend.x25519_supported(),
- skip_message="Requires OpenSSL with X25519 support"
+ skip_message="Requires OpenSSL with X25519 support",
)
class TestX25519Serialization(object):
def test_load_der_private_key(self, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", "X25519", "x25519-pkcs8-enc.der"),
lambda derfile: derfile.read(),
- mode="rb"
+ mode="rb",
)
unencrypted = load_vectors_from_file(
os.path.join("asymmetric", "X25519", "x25519-pkcs8.der"),
lambda derfile: derfile.read(),
- mode="rb"
+ mode="rb",
)
key = load_der_private_key(data, b"password", backend)
- assert key.private_bytes(
- Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
- ) == unencrypted
+ assert (
+ key.private_bytes(
+ Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
def test_load_pem_private_key(self, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", "X25519", "x25519-pkcs8-enc.pem"),
lambda pemfile: pemfile.read(),
- mode="rb"
+ mode="rb",
)
unencrypted = load_vectors_from_file(
os.path.join("asymmetric", "X25519", "x25519-pkcs8.pem"),
lambda pemfile: pemfile.read(),
- mode="rb"
+ mode="rb",
)
key = load_pem_private_key(data, b"password", backend)
- assert key.private_bytes(
- Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
- ) == unencrypted
+ assert (
+ key.private_bytes(
+ Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
@pytest.mark.parametrize(
("key_path", "encoding", "loader"),
[
- (
- ["X25519", "x25519-pub.pem"],
- Encoding.PEM,
- load_pem_public_key
- ),
- (
- ["X25519", "x25519-pub.der"],
- Encoding.DER,
- load_der_public_key
- ),
- ]
+ (["X25519", "x25519-pub.pem"], Encoding.PEM, load_pem_public_key),
+ (["X25519", "x25519-pub.der"], Encoding.DER, load_der_public_key),
+ ],
)
def test_load_public_key(self, key_path, encoding, loader, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", *key_path),
lambda pemfile: pemfile.read(),
- mode="rb"
+ mode="rb",
)
public_key = loader(data, backend)
- assert public_key.public_bytes(
- encoding, PublicFormat.SubjectPublicKeyInfo
- ) == data
+ assert (
+ public_key.public_bytes(
+ encoding, PublicFormat.SubjectPublicKeyInfo
+ )
+ == data
+ )
+
+ def test_openssl_serialization_unsupported(self, backend):
+ key = x25519.X25519PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.DER,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+
+ def test_openssh_serialization_unsupported(self, backend):
+ key = x25519.X25519PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM, PrivateFormat.OpenSSH, NoEncryption()
+ )
+
+
+@pytest.mark.supported(
+ only_if=lambda backend: backend.ed448_supported(),
+ skip_message="Requires OpenSSL with Ed448 support",
+)
+class TestEd448Serialization(object):
+ def test_load_der_private_key(self, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed448", "ed448-pkcs8-enc.der"),
+ lambda derfile: derfile.read(),
+ mode="rb",
+ )
+ unencrypted = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed448", "ed448-pkcs8.der"),
+ lambda derfile: derfile.read(),
+ mode="rb",
+ )
+ key = load_der_private_key(data, b"password", backend)
+ assert (
+ key.private_bytes(
+ Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
+
+ def test_load_pem_private_key(self, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed448", "ed448-pkcs8-enc.pem"),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ unencrypted = load_vectors_from_file(
+ os.path.join("asymmetric", "Ed448", "ed448-pkcs8.pem"),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ key = load_pem_private_key(data, b"password", backend)
+ assert (
+ key.private_bytes(
+ Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
+ )
+ == unencrypted
+ )
+
+ @pytest.mark.parametrize(
+ ("key_path", "encoding", "loader"),
+ [
+ (["Ed448", "ed448-pub.pem"], Encoding.PEM, load_pem_public_key),
+ (["Ed448", "ed448-pub.der"], Encoding.DER, load_der_public_key),
+ ],
+ )
+ def test_load_public_key(self, key_path, encoding, loader, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", *key_path),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ public_key = loader(data, backend)
+ assert (
+ public_key.public_bytes(
+ encoding, PublicFormat.SubjectPublicKeyInfo
+ )
+ == data
+ )
+
+ def test_openssl_serialization_unsupported(self, backend):
+ key = ed448.Ed448PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.DER,
+ PrivateFormat.TraditionalOpenSSL,
+ NoEncryption(),
+ )
+
+ def test_openssh_serialization_unsupported(self, backend):
+ key = ed448.Ed448PrivateKey.generate()
+ with pytest.raises(ValueError):
+ key.public_key().public_bytes(
+ Encoding.OpenSSH,
+ PublicFormat.OpenSSH,
+ )
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.OpenSSH,
+ NoEncryption(),
+ )
+
+
+class TestDHSerialization(object):
+ """Test all options with least-supported key type."""
+
+ @pytest.mark.skip_fips(reason="non-FIPS parameters")
+ def test_dh_public_key(self, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", "DH", "dhkey.pem"),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ public_key = load_pem_private_key(data, None, backend).public_key()
+ for enc in (
+ Encoding.PEM,
+ Encoding.DER,
+ Encoding.OpenSSH,
+ Encoding.Raw,
+ Encoding.X962,
+ ):
+ for fmt in (
+ PublicFormat.SubjectPublicKeyInfo,
+ PublicFormat.PKCS1,
+ PublicFormat.OpenSSH,
+ PublicFormat.Raw,
+ PublicFormat.CompressedPoint,
+ PublicFormat.UncompressedPoint,
+ ):
+ if (
+ enc in (Encoding.PEM, Encoding.DER)
+ and fmt == PublicFormat.SubjectPublicKeyInfo
+ ):
+ # tested elsewhere
+ continue
+ with pytest.raises(ValueError):
+ public_key.public_bytes(enc, fmt)
+
+ @pytest.mark.skip_fips(reason="non-FIPS parameters")
+ def test_dh_private_key(self, backend):
+ data = load_vectors_from_file(
+ os.path.join("asymmetric", "DH", "dhkey.pem"),
+ lambda pemfile: pemfile.read(),
+ mode="rb",
+ )
+ private_key = load_pem_private_key(data, None, backend)
+ for enc in (
+ Encoding.PEM,
+ Encoding.DER,
+ Encoding.OpenSSH,
+ Encoding.Raw,
+ Encoding.X962,
+ ):
+ for fmt in (
+ PrivateFormat.PKCS8,
+ PrivateFormat.TraditionalOpenSSL,
+ PrivateFormat.Raw,
+ ):
+ if (
+ enc in (Encoding.PEM, Encoding.DER)
+ and fmt is PrivateFormat.PKCS8
+ ):
+ # tested elsewhere
+ continue
+ with pytest.raises(ValueError):
+ private_key.private_bytes(enc, fmt, NoEncryption())
+
+
+@pytest.mark.requires_backend_interface(interface=RSABackend)
+@pytest.mark.requires_backend_interface(interface=DSABackend)
+@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
+class TestOpenSSHSerialization(object):
+ @pytest.mark.parametrize(
+ ("key_file", "cert_file"),
+ [
+ ("rsa-psw.key.pub", None),
+ ("rsa-nopsw.key.pub", "rsa-nopsw.key-cert.pub"),
+ ("dsa-psw.key.pub", None),
+ ("dsa-nopsw.key.pub", "dsa-nopsw.key-cert.pub"),
+ ("ecdsa-psw.key.pub", None),
+ ("ecdsa-nopsw.key.pub", "ecdsa-nopsw.key-cert.pub"),
+ ("ed25519-psw.key.pub", None),
+ ("ed25519-nopsw.key.pub", "ed25519-nopsw.key-cert.pub"),
+ ],
+ )
+ def test_load_ssh_public_key(self, key_file, cert_file, backend):
+ if "ed25519" in key_file and not backend.ed25519_supported():
+ pytest.skip("Requires OpenSSL with Ed25519 support")
+
+ # normal public key
+ pub_data = load_vectors_from_file(
+ os.path.join("asymmetric", "OpenSSH", key_file),
+ lambda f: f.read(),
+ mode="rb",
+ )
+ public_key = load_ssh_public_key(pub_data, backend)
+ nocomment_data = b" ".join(pub_data.split()[:2])
+ assert (
+ public_key.public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH)
+ == nocomment_data
+ )
+
+ self.run_partial_pubkey(pub_data, backend)
+
+ # parse public key with ssh certificate
+ if cert_file:
+ cert_data = load_vectors_from_file(
+ os.path.join("asymmetric", "OpenSSH", cert_file),
+ lambda f: f.read(),
+ mode="rb",
+ )
+ cert_key = load_ssh_public_key(cert_data, backend)
+ assert (
+ cert_key.public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH)
+ == nocomment_data
+ )
+
+ # try with more spaces
+ cert_data = b" \t ".join(cert_data.split())
+ cert_key = load_ssh_public_key(cert_data, backend)
+ assert (
+ cert_key.public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH)
+ == nocomment_data
+ )
+
+ self.run_partial_pubkey(cert_data, backend)
+
+ def run_partial_pubkey(self, pubdata, backend):
+ parts = pubdata.split()
+ raw = base64.b64decode(parts[1])
+ for i in range(1, len(raw)):
+ frag = base64.b64encode(raw[:i])
+ new_pub = b" ".join([parts[0], frag])
+ with pytest.raises(ValueError):
+ load_ssh_public_key(new_pub, backend)
+
+ @pytest.mark.parametrize(
+ ("key_file",),
+ [
+ ("rsa-nopsw.key",),
+ ("rsa-psw.key",),
+ ("dsa-nopsw.key",),
+ ("dsa-psw.key",),
+ ("ecdsa-nopsw.key",),
+ ("ecdsa-psw.key",),
+ ("ed25519-nopsw.key",),
+ ("ed25519-psw.key",),
+ ],
+ )
+ def test_load_ssh_private_key(self, key_file, backend):
+ if "ed25519" in key_file and not backend.ed25519_supported():
+ pytest.skip("Requires OpenSSL with Ed25519 support")
+ if "-psw" in key_file and not ssh._bcrypt_supported:
+ pytest.skip("Requires bcrypt module")
+
+ # read public and private key from ssh-keygen
+ priv_data = load_vectors_from_file(
+ os.path.join("asymmetric", "OpenSSH", key_file),
+ lambda f: f.read(),
+ mode="rb",
+ )
+ pub_data = load_vectors_from_file(
+ os.path.join("asymmetric", "OpenSSH", key_file + ".pub"),
+ lambda f: f.read(),
+ mode="rb",
+ )
+ nocomment_data = b" ".join(pub_data.split()[:2])
+
+ # load and compare
+ password = None
+ if "-psw" in key_file:
+ password = b"password"
+ private_key = load_ssh_private_key(priv_data, password, backend)
+ assert (
+ private_key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ == nocomment_data
+ )
+
+ # bytearray
+ private_key = load_ssh_private_key(
+ bytearray(priv_data), password, backend
+ )
+ assert (
+ private_key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ == nocomment_data
+ )
+
+ if six.PY3:
+ # memoryview(bytes)
+ private_key = load_ssh_private_key(
+ memoryview(priv_data), password, backend
+ )
+ assert (
+ private_key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ == nocomment_data
+ )
+
+ # memoryview(bytearray)
+ private_key = load_ssh_private_key(
+ memoryview(bytearray(priv_data)), password, backend
+ )
+ assert (
+ private_key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ == nocomment_data
+ )
+
+ # serialize with own code and reload
+ encryption = NoEncryption()
+ if password:
+ encryption = BestAvailableEncryption(password)
+ priv_data2 = private_key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.OpenSSH,
+ encryption,
+ )
+ private_key2 = load_ssh_private_key(priv_data2, password, backend)
+ assert (
+ private_key2.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ == nocomment_data
+ )
+
+ # make sure multi-line base64 is used
+ maxline = max(map(len, priv_data2.split(b"\n")))
+ assert maxline < 80
+
+ @pytest.mark.supported(
+ only_if=lambda backend: ssh._bcrypt_supported,
+ skip_message="Requires that bcrypt exists",
+ )
+ def test_bcrypt_encryption(self, backend):
+ private_key = ec.generate_private_key(ec.SECP256R1(), backend)
+ pub1 = private_key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+
+ for psw in (
+ b"1",
+ b"1234",
+ b"1234" * 4,
+ b"x" * 72,
+ ):
+ # BestAvailableEncryption does not handle bytes-like?
+ best = BestAvailableEncryption(psw)
+ encdata = private_key.private_bytes(
+ Encoding.PEM, PrivateFormat.OpenSSH, best
+ )
+ decoded_key = load_ssh_private_key(encdata, psw, backend)
+ pub2 = decoded_key.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ assert pub1 == pub2
+
+ # bytearray
+ decoded_key2 = load_ssh_private_key(
+ bytearray(encdata), psw, backend
+ )
+ pub2 = decoded_key2.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ assert pub1 == pub2
+
+ if six.PY3:
+ # memoryview(bytes)
+ decoded_key2 = load_ssh_private_key(
+ memoryview(encdata), psw, backend
+ )
+ pub2 = decoded_key2.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ assert pub1 == pub2
+
+ # memoryview(bytearray)
+ decoded_key2 = load_ssh_private_key(
+ memoryview(bytearray(encdata)), psw, backend
+ )
+ pub2 = decoded_key2.public_key().public_bytes(
+ Encoding.OpenSSH, PublicFormat.OpenSSH
+ )
+ assert pub1 == pub2
+
+ with pytest.raises(ValueError):
+ decoded_key = load_ssh_private_key(encdata, None, backend)
+ with pytest.raises(ValueError):
+ decoded_key = load_ssh_private_key(encdata, b"wrong", backend)
+
+ @pytest.mark.supported(
+ only_if=lambda backend: not ssh._bcrypt_supported,
+ skip_message="Requires that bcrypt is missing",
+ )
+ def test_missing_bcrypt(self, backend):
+ priv_data = load_vectors_from_file(
+ os.path.join("asymmetric", "OpenSSH", "ecdsa-psw.key"),
+ lambda f: f.read(),
+ mode="rb",
+ )
+ with pytest.raises(UnsupportedAlgorithm):
+ load_ssh_private_key(priv_data, b"password", backend)
+
+ private_key = ec.generate_private_key(ec.SECP256R1(), backend)
+ with pytest.raises(UnsupportedAlgorithm):
+ private_key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.OpenSSH,
+ BestAvailableEncryption(b"x"),
+ )
+
+ def test_fraglist_corners(self):
+ f = ssh._FragList()
+ with pytest.raises(ValueError):
+ f.put_mpint(-1)
+ f.put_mpint(0)
+ f.put_mpint(0x80)
+ assert f.tobytes() == b"\0\0\0\0" + b"\0\0\0\x02" + b"\0\x80"
+
+ def make_file(
+ self,
+ magic=b"openssh-key-v1\0",
+ ciphername=b"none",
+ kdfname=b"none",
+ kdfoptions=b"",
+ nkeys=1,
+ pub_type=b"ecdsa-sha2-nistp256",
+ pub_fields=(
+ b"nistp256",
+ b"\x04" * 65,
+ ),
+ priv_type=None,
+ priv_fields=(b"nistp256", b"\x04" * 65, b"\x7F" * 32),
+ comment=b"comment",
+ checkval1=b"1234",
+ checkval2=b"1234",
+ pad=None,
+ header=b"-----BEGIN OPENSSH PRIVATE KEY-----\n",
+ footer=b"-----END OPENSSH PRIVATE KEY-----\n",
+ cut=8192,
+ ):
+ """Create private key file"""
+ if not priv_type:
+ priv_type = pub_type
+
+ pub = ssh._FragList()
+ for elem in (pub_type,) + pub_fields:
+ pub.put_sshstr(elem)
+
+ secret = ssh._FragList([checkval1, checkval2])
+ for i in range(nkeys):
+ for elem in (priv_type,) + priv_fields + (comment,):
+ secret.put_sshstr(elem)
+
+ if pad is None:
+ pad_len = 8 - (secret.size() % 8)
+ pad = bytearray(range(1, 1 + pad_len))
+ secret.put_raw(pad)
+
+ main = ssh._FragList([magic])
+ main.put_sshstr(ciphername)
+ main.put_sshstr(kdfname)
+ main.put_sshstr(kdfoptions)
+ main.put_u32(nkeys)
+ for i in range(nkeys):
+ main.put_sshstr(pub)
+ main.put_sshstr(secret)
+
+ res = main.tobytes()
+ return ssh._ssh_pem_encode(res[:cut], header, footer)
+
+ def test_ssh_make_file(self, backend):
+ # check if works by default
+ data = self.make_file()
+ key = load_ssh_private_key(data, None, backend)
+ assert isinstance(key, ec.EllipticCurvePrivateKey)
+
+ def test_load_ssh_private_key_errors(self, backend):
+ # bad kdf
+ data = self.make_file(kdfname=b"unknown", ciphername=b"aes256-ctr")
+ with pytest.raises(UnsupportedAlgorithm):
+ load_ssh_private_key(data, None, backend)
+
+ # bad cipher
+ data = self.make_file(ciphername=b"unknown", kdfname=b"bcrypt")
+ with pytest.raises(UnsupportedAlgorithm):
+ load_ssh_private_key(data, None, backend)
+
+ # bad magic
+ data = self.make_file(magic=b"unknown")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # too few keys
+ data = self.make_file(nkeys=0)
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # too many keys
+ data = self.make_file(nkeys=2)
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ def test_ssh_errors_bad_values(self, backend):
+ # bad curve
+ data = self.make_file(pub_type=b"ecdsa-sha2-nistp444")
+ with pytest.raises(UnsupportedAlgorithm):
+ load_ssh_private_key(data, None, backend)
+
+ # curve mismatch
+ data = self.make_file(priv_type=b"ecdsa-sha2-nistp384")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # invalid bigint
+ data = self.make_file(
+ priv_fields=(b"nistp256", b"\x04" * 65, b"\x80" * 32)
+ )
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ def test_ssh_errors_pubpriv_mismatch(self, backend):
+ # ecdsa public-private mismatch
+ data = self.make_file(
+ pub_fields=(
+ b"nistp256",
+ b"\x04" + b"\x05" * 64,
+ )
+ )
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # rsa public-private mismatch
+ data = self.make_file(
+ pub_type=b"ssh-rsa",
+ pub_fields=(b"x" * 32,) * 2,
+ priv_fields=(b"z" * 32,) * 6,
+ )
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # dsa public-private mismatch
+ data = self.make_file(
+ pub_type=b"ssh-dss",
+ pub_fields=(b"x" * 32,) * 4,
+ priv_fields=(b"z" * 32,) * 5,
+ )
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # ed25519 public-private mismatch
+ sk = b"x" * 32
+ pk1 = b"y" * 32
+ pk2 = b"z" * 32
+ data = self.make_file(
+ pub_type=b"ssh-ed25519",
+ pub_fields=(pk1,),
+ priv_fields=(
+ pk1,
+ sk + pk2,
+ ),
+ )
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+ data = self.make_file(
+ pub_type=b"ssh-ed25519",
+ pub_fields=(pk1,),
+ priv_fields=(
+ pk2,
+ sk + pk1,
+ ),
+ )
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ def test_ssh_errors_bad_wrapper(self, backend):
+ # wrong header
+ data = self.make_file(header=b"-----BEGIN RSA PRIVATE KEY-----\n")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # wring footer
+ data = self.make_file(footer=b"-----END RSA PRIVATE KEY-----\n")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ def test_ssh_no_padding(self, backend):
+ # no padding must work, if data is on block boundary
+ data = self.make_file(pad=b"", comment=b"")
+ key = load_ssh_private_key(data, None, backend)
+ assert isinstance(key, ec.EllipticCurvePrivateKey)
+
+ # no padding with right last byte
+ data = self.make_file(pad=b"", comment=b"\x08" * 8)
+ key = load_ssh_private_key(data, None, backend)
+ assert isinstance(key, ec.EllipticCurvePrivateKey)
+
+ # avoid unexpected padding removal
+ data = self.make_file(pad=b"", comment=b"1234\x01\x02\x03\x04")
+ key = load_ssh_private_key(data, None, backend)
+ assert isinstance(key, ec.EllipticCurvePrivateKey)
+
+ # bad padding with right size
+ data = self.make_file(pad=b"\x08" * 8, comment=b"")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ def test_ssh_errors_bad_secrets(self, backend):
+ # checkval mismatch
+ data = self.make_file(checkval2=b"4321")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ # bad padding, correct=1
+ data = self.make_file(pad=b"\x01\x02")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+ data = self.make_file(pad=b"")
+ with pytest.raises(ValueError):
+ load_ssh_private_key(data, None, backend)
+
+ @pytest.mark.supported(
+ only_if=lambda backend: backend.elliptic_curve_supported(
+ ec.SECP192R1()
+ ),
+ skip_message="Requires backend support for ec.SECP192R1",
+ )
+ def test_serialize_ssh_private_key_errors_bad_curve(self, backend):
+ private_key = ec.generate_private_key(ec.SECP192R1(), backend)
+ with pytest.raises(ValueError):
+ private_key.private_bytes(
+ Encoding.PEM, PrivateFormat.OpenSSH, NoEncryption()
+ )
+
+ def test_serialize_ssh_private_key_errors(self, backend):
+ # bad encoding
+ private_key = ec.generate_private_key(ec.SECP256R1(), backend)
+ with pytest.raises(ValueError):
+ private_key.private_bytes(
+ Encoding.DER, PrivateFormat.OpenSSH, NoEncryption()
+ )
+
+ # bad object type
+ with pytest.raises(ValueError):
+ ssh.serialize_ssh_private_key(object(), None)
+
+ private_key = ec.generate_private_key(ec.SECP256R1(), backend)
+
+ # too long password
+ with pytest.raises(ValueError):
+ private_key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.OpenSSH,
+ BestAvailableEncryption(b"p" * 73),
+ )
+
+ # unknown encryption class
+ with pytest.raises(ValueError):
+ private_key.private_bytes(
+ Encoding.PEM,
+ PrivateFormat.OpenSSH,
+ DummyKeySerializationEncryption(),
+ )
+
+ @pytest.mark.parametrize(
+ ("key_path", "supported"),
+ [
+ (["Traditional_OpenSSL_Serialization", "dsa.1024.pem"], True),
+ (["Traditional_OpenSSL_Serialization", "dsa.2048.pem"], False),
+ (["Traditional_OpenSSL_Serialization", "dsa.3072.pem"], False),
+ ],
+ )
+ def test_dsa_private_key_sizes(self, key_path, supported, backend):
+ key = load_vectors_from_file(
+ os.path.join("asymmetric", *key_path),
+ lambda pemfile: load_pem_private_key(
+ pemfile.read(), None, backend
+ ),
+ mode="rb",
+ )
+ assert isinstance(key, dsa.DSAPrivateKey)
+ if supported:
+ res = key.private_bytes(
+ Encoding.PEM, PrivateFormat.OpenSSH, NoEncryption()
+ )
+ assert isinstance(res, bytes)
+ else:
+ with pytest.raises(ValueError):
+ key.private_bytes(
+ Encoding.PEM, PrivateFormat.OpenSSH, NoEncryption()
+ )
diff --git a/tests/hazmat/primitives/test_x25519.py b/tests/hazmat/primitives/test_x25519.py
index 17a9115..fd1137d 100644
--- a/tests/hazmat/primitives/test_x25519.py
+++ b/tests/hazmat/primitives/test_x25519.py
@@ -9,24 +9,24 @@
import pytest
-from cryptography import utils
from cryptography.exceptions import _Reasons
-from cryptography.hazmat.backends.interfaces import DHBackend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.x25519 import (
- X25519PrivateKey, X25519PublicKey
+ X25519PrivateKey,
+ X25519PublicKey,
)
from ...utils import (
- load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
@pytest.mark.supported(
only_if=lambda backend: not backend.x25519_supported(),
- skip_message="Requires OpenSSL without X25519 support"
+ skip_message="Requires OpenSSL without X25519 support",
)
-@pytest.mark.requires_backend_interface(interface=DHBackend)
def test_x25519_unsupported(backend):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM):
X25519PublicKey.from_public_bytes(b"0" * 32)
@@ -40,16 +40,15 @@
@pytest.mark.supported(
only_if=lambda backend: backend.x25519_supported(),
- skip_message="Requires OpenSSL with X25519 support"
+ skip_message="Requires OpenSSL with X25519 support",
)
-@pytest.mark.requires_backend_interface(interface=DHBackend)
class TestX25519Exchange(object):
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "X25519", "rfc7748.txt"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_rfc7748(self, vector, backend):
private = binascii.unhexlify(vector["input_scalar"])
@@ -91,23 +90,16 @@
private = binascii.unhexlify(
"78f1e8edf14481b389448dac8f59c70b038e7cf92ef2c7eff57a72466e115296"
)
- private_key = X25519PrivateKey.from_private_bytes(
- private
- )
+ private_key = X25519PrivateKey.from_private_bytes(private)
public_key = X25519PublicKey.from_public_bytes(public)
with pytest.raises(ValueError):
private_key.exchange(public_key)
- def test_deprecated_public_bytes(self, backend):
- key = X25519PrivateKey.generate().public_key()
- with pytest.warns(utils.DeprecatedIn25):
- key.public_bytes()
-
def test_public_bytes_bad_args(self, backend):
key = X25519PrivateKey.generate().public_key()
with pytest.raises(ValueError):
key.public_bytes(None, serialization.PublicFormat.Raw)
- with pytest.raises(ValueError):
+ with pytest.raises(TypeError):
key.public_bytes(serialization.Encoding.Raw)
# These vectors are also from RFC 7748
@@ -123,7 +115,7 @@
binascii.unhexlify(
b"8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98"
b"eaa9b4e6a"
- )
+ ),
),
(
binascii.unhexlify(
@@ -133,24 +125,33 @@
binascii.unhexlify(
b"de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e1"
b"46f882b4f"
- )
- )
- ]
+ ),
+ ),
+ ],
)
def test_pub_priv_bytes_raw(self, private_bytes, public_bytes, backend):
private_key = X25519PrivateKey.from_private_bytes(private_bytes)
- assert private_key.private_bytes(
- serialization.Encoding.Raw,
- serialization.PrivateFormat.Raw,
- serialization.NoEncryption()
- ) == private_bytes
- assert private_key.public_key().public_bytes(
- serialization.Encoding.Raw, serialization.PublicFormat.Raw
- ) == public_bytes
+ assert (
+ private_key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+ == private_bytes
+ )
+ assert (
+ private_key.public_key().public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == public_bytes
+ )
public_key = X25519PublicKey.from_public_bytes(public_bytes)
- assert public_key.public_bytes(
- serialization.Encoding.Raw, serialization.PublicFormat.Raw
- ) == public_bytes
+ assert (
+ public_key.public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == public_bytes
+ )
def test_generate(self, backend):
key = X25519PrivateKey.generate()
@@ -182,21 +183,21 @@
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
- None
+ None,
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.PKCS8,
- None
+ None,
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.Raw,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_invalid_public_bytes(self, backend):
@@ -204,19 +205,17 @@
with pytest.raises(ValueError):
key.public_bytes(
serialization.Encoding.Raw,
- serialization.PublicFormat.SubjectPublicKeyInfo
+ serialization.PublicFormat.SubjectPublicKeyInfo,
)
with pytest.raises(ValueError):
key.public_bytes(
- serialization.Encoding.PEM,
- serialization.PublicFormat.PKCS1
+ serialization.Encoding.PEM, serialization.PublicFormat.PKCS1
)
with pytest.raises(ValueError):
key.public_bytes(
- serialization.Encoding.PEM,
- serialization.PublicFormat.Raw
+ serialization.Encoding.PEM, serialization.PublicFormat.Raw
)
@pytest.mark.parametrize(
@@ -227,33 +226,34 @@
serialization.PrivateFormat.PKCS8,
serialization.BestAvailableEncryption(b"password"),
b"password",
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
),
(
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.BestAvailableEncryption(b"password"),
b"password",
- serialization.load_der_private_key
+ serialization.load_der_private_key,
),
(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
None,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
),
(
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
None,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
),
- ]
+ ],
)
- def test_round_trip_private_serialization(self, encoding, fmt, encryption,
- passwd, load_func, backend):
+ def test_round_trip_private_serialization(
+ self, encoding, fmt, encryption, passwd, load_func, backend
+ ):
key = X25519PrivateKey.generate()
serialized = key.private_bytes(encoding, fmt, encryption)
loaded_key = load_func(serialized, passwd, backend)
@@ -262,8 +262,11 @@
def test_buffer_protocol(self, backend):
private_bytes = bytearray(os.urandom(32))
key = X25519PrivateKey.from_private_bytes(private_bytes)
- assert key.private_bytes(
- serialization.Encoding.Raw,
- serialization.PrivateFormat.Raw,
- serialization.NoEncryption()
- ) == private_bytes
+ assert (
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+ == private_bytes
+ )
diff --git a/tests/hazmat/primitives/test_x448.py b/tests/hazmat/primitives/test_x448.py
index 817de76..7b19b65 100644
--- a/tests/hazmat/primitives/test_x448.py
+++ b/tests/hazmat/primitives/test_x448.py
@@ -10,22 +10,23 @@
import pytest
from cryptography.exceptions import _Reasons
-from cryptography.hazmat.backends.interfaces import DHBackend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.x448 import (
- X448PrivateKey, X448PublicKey
+ X448PrivateKey,
+ X448PublicKey,
)
from ...utils import (
- load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
@pytest.mark.supported(
only_if=lambda backend: not backend.x448_supported(),
- skip_message="Requires OpenSSL without X448 support"
+ skip_message="Requires OpenSSL without X448 support",
)
-@pytest.mark.requires_backend_interface(interface=DHBackend)
def test_x448_unsupported(backend):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM):
X448PublicKey.from_public_bytes(b"0" * 56)
@@ -39,16 +40,15 @@
@pytest.mark.supported(
only_if=lambda backend: backend.x448_supported(),
- skip_message="Requires OpenSSL with X448 support"
+ skip_message="Requires OpenSSL with X448 support",
)
-@pytest.mark.requires_backend_interface(interface=DHBackend)
class TestX448Exchange(object):
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "X448", "rfc7748.txt"),
- load_nist_vectors
- )
+ load_nist_vectors,
+ ),
)
def test_rfc7748(self, vector, backend):
private = binascii.unhexlify(vector["input_scalar"])
@@ -93,7 +93,7 @@
binascii.unhexlify(
b"9b08f7cc31b7e3e67d22d5aea121074a273bd2b83de09c63faa73d2c"
b"22c5d9bbc836647241d953d40c5b12da88120d53177f80e532c41fa0"
- )
+ ),
),
(
binascii.unhexlify(
@@ -103,24 +103,33 @@
binascii.unhexlify(
b"3eb7a829b0cd20f5bcfc0b599b6feccf6da4627107bdb0d4f345b430"
b"27d8b972fc3e34fb4232a13ca706dcb57aec3dae07bdc1c67bf33609"
- )
- )
- ]
+ ),
+ ),
+ ],
)
def test_pub_priv_bytes_raw(self, private_bytes, public_bytes, backend):
private_key = X448PrivateKey.from_private_bytes(private_bytes)
- assert private_key.private_bytes(
- serialization.Encoding.Raw,
- serialization.PrivateFormat.Raw,
- serialization.NoEncryption()
- ) == private_bytes
- assert private_key.public_key().public_bytes(
- serialization.Encoding.Raw, serialization.PublicFormat.Raw
- ) == public_bytes
+ assert (
+ private_key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+ == private_bytes
+ )
+ assert (
+ private_key.public_key().public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == public_bytes
+ )
public_key = X448PublicKey.from_public_bytes(public_bytes)
- assert public_key.public_bytes(
- serialization.Encoding.Raw, serialization.PublicFormat.Raw
- ) == public_bytes
+ assert (
+ public_key.public_bytes(
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
+ )
+ == public_bytes
+ )
@pytest.mark.parametrize(
("encoding", "fmt", "encryption", "passwd", "load_func"),
@@ -130,33 +139,34 @@
serialization.PrivateFormat.PKCS8,
serialization.BestAvailableEncryption(b"password"),
b"password",
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
),
(
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.BestAvailableEncryption(b"password"),
b"password",
- serialization.load_der_private_key
+ serialization.load_der_private_key,
),
(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
None,
- serialization.load_pem_private_key
+ serialization.load_pem_private_key,
),
(
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
None,
- serialization.load_der_private_key
+ serialization.load_der_private_key,
),
- ]
+ ],
)
- def test_round_trip_private_serialization(self, encoding, fmt, encryption,
- passwd, load_func, backend):
+ def test_round_trip_private_serialization(
+ self, encoding, fmt, encryption, passwd, load_func, backend
+ ):
key = X448PrivateKey.generate()
serialized = key.private_bytes(encoding, fmt, encryption)
loaded_key = load_func(serialized, passwd, backend)
@@ -192,21 +202,21 @@
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
- None
+ None,
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.PKCS8,
- None
+ None,
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.Raw,
- serialization.NoEncryption()
+ serialization.NoEncryption(),
)
def test_invalid_public_bytes(self, backend):
@@ -214,19 +224,17 @@
with pytest.raises(ValueError):
key.public_bytes(
serialization.Encoding.Raw,
- serialization.PublicFormat.SubjectPublicKeyInfo
+ serialization.PublicFormat.SubjectPublicKeyInfo,
)
with pytest.raises(ValueError):
key.public_bytes(
- serialization.Encoding.PEM,
- serialization.PublicFormat.PKCS1
+ serialization.Encoding.PEM, serialization.PublicFormat.PKCS1
)
with pytest.raises(ValueError):
key.public_bytes(
- serialization.Encoding.PEM,
- serialization.PublicFormat.Raw
+ serialization.Encoding.PEM, serialization.PublicFormat.Raw
)
def test_buffer_protocol(self, backend):
@@ -235,8 +243,11 @@
b"d9c9baf574a9419744897391006382a6f127ab1d9ac2d8c0a598726b"
)
key = X448PrivateKey.from_private_bytes(bytearray(private_bytes))
- assert key.private_bytes(
- serialization.Encoding.Raw,
- serialization.PrivateFormat.Raw,
- serialization.NoEncryption()
- ) == private_bytes
+ assert (
+ key.private_bytes(
+ serialization.Encoding.Raw,
+ serialization.PrivateFormat.Raw,
+ serialization.NoEncryption(),
+ )
+ == private_bytes
+ )
diff --git a/tests/hazmat/primitives/test_x963_vectors.py b/tests/hazmat/primitives/test_x963_vectors.py
index 4a945d4..e3b54fc 100644
--- a/tests/hazmat/primitives/test_x963_vectors.py
+++ b/tests/hazmat/primitives/test_x963_vectors.py
@@ -9,7 +9,6 @@
import pytest
-from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.backends.interfaces import HashBackend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
@@ -21,7 +20,7 @@
def _skip_hashfn_unsupported(backend, hashfn):
if not backend.hash_supported(hashfn):
pytest.skip(
- "Hash {0} is not supported by this backend {1}".format(
+ "Hash {} is not supported by this backend {}".format(
hashfn.name, backend
)
)
@@ -30,19 +29,18 @@
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestX963(object):
_algorithms_dict = {
- 'SHA-1': hashes.SHA1,
- 'SHA-224': hashes.SHA224,
- 'SHA-256': hashes.SHA256,
- 'SHA-384': hashes.SHA384,
- 'SHA-512': hashes.SHA512
+ "SHA-1": hashes.SHA1,
+ "SHA-224": hashes.SHA224,
+ "SHA-256": hashes.SHA256,
+ "SHA-384": hashes.SHA384,
+ "SHA-512": hashes.SHA512,
}
@pytest.mark.parametrize(
("vector"),
load_vectors_from_file(
- os.path.join("KDF", "ansx963_2001.txt"),
- load_x963_vectors
- )
+ os.path.join("KDF", "ansx963_2001.txt"), load_x963_vectors
+ ),
)
def test_x963(self, backend, vector):
hashfn = self._algorithms_dict[vector["hash"]]
@@ -55,10 +53,12 @@
key_data_len = vector["key_data_length"] // 8
key_data = binascii.unhexlify(vector["key_data"])
- xkdf = X963KDF(algorithm=hashfn(),
- length=key_data_len,
- sharedinfo=sharedinfo,
- backend=default_backend())
+ xkdf = X963KDF(
+ algorithm=hashfn(),
+ length=key_data_len,
+ sharedinfo=sharedinfo,
+ backend=backend,
+ )
xkdf.verify(key, key_data)
def test_unsupported_hash(self, backend):
diff --git a/tests/hazmat/primitives/test_x963kdf.py b/tests/hazmat/primitives/test_x963kdf.py
index c4dd892..5040ae4 100644
--- a/tests/hazmat/primitives/test_x963kdf.py
+++ b/tests/hazmat/primitives/test_x963kdf.py
@@ -8,9 +8,7 @@
import pytest
-from cryptography.exceptions import (
- AlreadyFinalized, InvalidKey, _Reasons
-)
+from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons
from cryptography.hazmat.backends.interfaces import HashBackend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
@@ -46,9 +44,11 @@
assert xkdf.derive(key) == derivedkey
def test_buffer_protocol(self, backend):
- key = bytearray(binascii.unhexlify(
- b"96c05619d56c328ab95fe84b18264b08725b85e33fd34f08"
- ))
+ key = bytearray(
+ binascii.unhexlify(
+ b"96c05619d56c328ab95fe84b18264b08725b85e33fd34f08"
+ )
+ )
derivedkey = binascii.unhexlify(b"443024c3dae66b95e6f5670601558f71")
@@ -86,39 +86,25 @@
def test_unicode_typeerror(self, backend):
with pytest.raises(TypeError):
- X963KDF(
- hashes.SHA256(),
- 16,
- sharedinfo=u"foo",
- backend=backend
- )
+ X963KDF(hashes.SHA256(), 16, sharedinfo=u"foo", backend=backend)
with pytest.raises(TypeError):
xkdf = X963KDF(
- hashes.SHA256(),
- 16,
- sharedinfo=None,
- backend=backend
+ hashes.SHA256(), 16, sharedinfo=None, backend=backend
)
xkdf.derive(u"foo")
with pytest.raises(TypeError):
xkdf = X963KDF(
- hashes.SHA256(),
- 16,
- sharedinfo=None,
- backend=backend
+ hashes.SHA256(), 16, sharedinfo=None, backend=backend
)
xkdf.verify(u"foo", b"bar")
with pytest.raises(TypeError):
xkdf = X963KDF(
- hashes.SHA256(),
- 16,
- sharedinfo=None,
- backend=backend
+ hashes.SHA256(), 16, sharedinfo=None, backend=backend
)
xkdf.verify(b"foo", u"bar")
diff --git a/tests/hazmat/primitives/twofactor/test_hotp.py b/tests/hazmat/primitives/twofactor/test_hotp.py
index 14cb08a..08bfd7e 100644
--- a/tests/hazmat/primitives/twofactor/test_hotp.py
+++ b/tests/hazmat/primitives/twofactor/test_hotp.py
@@ -16,16 +16,17 @@
from cryptography.hazmat.primitives.twofactor.hotp import HOTP
from ....utils import (
- load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
-vectors = load_vectors_from_file(
- "twofactor/rfc-4226.txt", load_nist_vectors)
+vectors = load_vectors_from_file("twofactor/rfc-4226.txt", load_nist_vectors)
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA1()),
- skip_message="Does not support HMAC-SHA1."
+ skip_message="Does not support HMAC-SHA1.",
)
@pytest.mark.requires_backend_interface(interface=HMACBackend)
class TestHOTP(object):
@@ -102,12 +103,14 @@
assert hotp.get_provisioning_uri("Alice Smith", 1, None) == (
"otpauth://hotp/Alice%20Smith?digits=6&secret=GEZDGNBV"
- "GY3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&counter=1")
+ "GY3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&counter=1"
+ )
- assert hotp.get_provisioning_uri("Alice Smith", 1, 'Foo') == (
+ assert hotp.get_provisioning_uri("Alice Smith", 1, "Foo") == (
"otpauth://hotp/Foo:Alice%20Smith?digits=6&secret=GEZD"
"GNBVGY3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&issuer=Foo"
- "&counter=1")
+ "&counter=1"
+ )
def test_buffer_protocol(self, backend):
key = bytearray(b"a long key with lots of entropy goes here")
diff --git a/tests/hazmat/primitives/twofactor/test_totp.py b/tests/hazmat/primitives/twofactor/test_totp.py
index 59d875a..06d8600 100644
--- a/tests/hazmat/primitives/twofactor/test_totp.py
+++ b/tests/hazmat/primitives/twofactor/test_totp.py
@@ -13,21 +13,23 @@
from cryptography.hazmat.primitives.twofactor.totp import TOTP
from ....utils import (
- load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm
+ load_nist_vectors,
+ load_vectors_from_file,
+ raises_unsupported_algorithm,
)
-vectors = load_vectors_from_file(
- "twofactor/rfc-6238.txt", load_nist_vectors)
+vectors = load_vectors_from_file("twofactor/rfc-6238.txt", load_nist_vectors)
@pytest.mark.requires_backend_interface(interface=HMACBackend)
class TestTOTP(object):
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA1()),
- skip_message="Does not support HMAC-SHA1."
+ skip_message="Does not support HMAC-SHA1.",
)
@pytest.mark.parametrize(
- "params", [i for i in vectors if i["mode"] == b"SHA1"])
+ "params", [i for i in vectors if i["mode"] == b"SHA1"]
+ )
def test_generate_sha1(self, backend, params):
secret = params["secret"]
time = int(params["time"])
@@ -38,10 +40,11 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA256()),
- skip_message="Does not support HMAC-SHA256."
+ skip_message="Does not support HMAC-SHA256.",
)
@pytest.mark.parametrize(
- "params", [i for i in vectors if i["mode"] == b"SHA256"])
+ "params", [i for i in vectors if i["mode"] == b"SHA256"]
+ )
def test_generate_sha256(self, backend, params):
secret = params["secret"]
time = int(params["time"])
@@ -52,10 +55,11 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA512()),
- skip_message="Does not support HMAC-SHA512."
+ skip_message="Does not support HMAC-SHA512.",
)
@pytest.mark.parametrize(
- "params", [i for i in vectors if i["mode"] == b"SHA512"])
+ "params", [i for i in vectors if i["mode"] == b"SHA512"]
+ )
def test_generate_sha512(self, backend, params):
secret = params["secret"]
time = int(params["time"])
@@ -66,10 +70,11 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA1()),
- skip_message="Does not support HMAC-SHA1."
+ skip_message="Does not support HMAC-SHA1.",
)
@pytest.mark.parametrize(
- "params", [i for i in vectors if i["mode"] == b"SHA1"])
+ "params", [i for i in vectors if i["mode"] == b"SHA1"]
+ )
def test_verify_sha1(self, backend, params):
secret = params["secret"]
time = int(params["time"])
@@ -81,10 +86,11 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA256()),
- skip_message="Does not support HMAC-SHA256."
+ skip_message="Does not support HMAC-SHA256.",
)
@pytest.mark.parametrize(
- "params", [i for i in vectors if i["mode"] == b"SHA256"])
+ "params", [i for i in vectors if i["mode"] == b"SHA256"]
+ )
def test_verify_sha256(self, backend, params):
secret = params["secret"]
time = int(params["time"])
@@ -96,10 +102,11 @@
@pytest.mark.supported(
only_if=lambda backend: backend.hmac_supported(hashes.SHA512()),
- skip_message="Does not support HMAC-SHA512."
+ skip_message="Does not support HMAC-SHA512.",
)
@pytest.mark.parametrize(
- "params", [i for i in vectors if i["mode"] == b"SHA512"])
+ "params", [i for i in vectors if i["mode"] == b"SHA512"]
+ )
def test_verify_sha512(self, backend, params):
secret = params["secret"]
time = int(params["time"])
@@ -132,12 +139,14 @@
assert totp.get_provisioning_uri("Alice Smith", None) == (
"otpauth://totp/Alice%20Smith?digits=6&secret=GEZDGNBVG"
- "Y3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&period=30")
+ "Y3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&period=30"
+ )
- assert totp.get_provisioning_uri("Alice Smith", 'World') == (
+ assert totp.get_provisioning_uri("Alice Smith", "World") == (
"otpauth://totp/World:Alice%20Smith?digits=6&secret=GEZ"
"DGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&issuer=World"
- "&period=30")
+ "&period=30"
+ )
def test_buffer_protocol(self, backend):
key = bytearray(b"a long key with lots of entropy goes here")
diff --git a/tests/hazmat/primitives/utils.py b/tests/hazmat/primitives/utils.py
index 811dcf9..3f1eff6 100644
--- a/tests/hazmat/primitives/utils.py
+++ b/tests/hazmat/primitives/utils.py
@@ -11,15 +11,21 @@
import pytest
from cryptography.exceptions import (
- AlreadyFinalized, AlreadyUpdated, InvalidSignature, InvalidTag,
- NotYetFinalized
+ AlreadyFinalized,
+ AlreadyUpdated,
+ InvalidSignature,
+ InvalidTag,
+ NotYetFinalized,
)
-from cryptography.hazmat.primitives import hashes, hmac
+from cryptography.hazmat.primitives import hashes, hmac, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.ciphers import Cipher
+from cryptography.hazmat.primitives.ciphers.modes import GCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF, HKDFExpand
from cryptography.hazmat.primitives.kdf.kbkdf import (
- CounterLocation, KBKDFHMAC, Mode
+ CounterLocation,
+ KBKDFHMAC,
+ Mode,
)
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
@@ -35,8 +41,9 @@
return all_params
-def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
- mode_factory):
+def generate_encrypt_test(
+ param_loader, path, file_names, cipher_factory, mode_factory
+):
all_params = _load_all_params(path, file_names, param_loader)
@pytest.mark.parametrize("params", all_params)
@@ -54,9 +61,7 @@
plaintext = params["plaintext"]
ciphertext = params["ciphertext"]
cipher = Cipher(
- cipher_factory(**params),
- mode_factory(**params),
- backend=backend
+ cipher_factory(**params), mode_factory(**params), backend=backend
)
encryptor = cipher.encryptor()
actual_ciphertext = encryptor.update(binascii.unhexlify(plaintext))
@@ -68,8 +73,9 @@
assert actual_plaintext == binascii.unhexlify(plaintext)
-def generate_aead_test(param_loader, path, file_names, cipher_factory,
- mode_factory):
+def generate_aead_test(
+ param_loader, path, file_names, cipher_factory, mode_factory
+):
all_params = _load_all_params(path, file_names, param_loader)
@pytest.mark.parametrize("params", all_params)
@@ -80,6 +86,20 @@
def aead_test(backend, cipher_factory, mode_factory, params):
+ if mode_factory is GCM and len(params["iv"]) < 16:
+ # 16 because this is hex encoded data
+ pytest.skip("Less than 64-bit IVs are no longer supported")
+
+ if (
+ mode_factory is GCM
+ and backend._fips_enabled
+ and len(params["iv"]) != 24
+ ):
+ # Red Hat disables non-96-bit IV support as part of its FIPS
+ # patches. The check is for a byte length of 24 because the value is
+ # hex encoded.
+ pytest.skip("Non-96-bit IVs unsupported in FIPS mode.")
+
if params.get("pt") is not None:
plaintext = params["pt"]
ciphertext = params["ct"]
@@ -87,10 +107,12 @@
if params.get("fail") is True:
cipher = Cipher(
cipher_factory(binascii.unhexlify(params["key"])),
- mode_factory(binascii.unhexlify(params["iv"]),
- binascii.unhexlify(params["tag"]),
- len(binascii.unhexlify(params["tag"]))),
- backend
+ mode_factory(
+ binascii.unhexlify(params["iv"]),
+ binascii.unhexlify(params["tag"]),
+ len(binascii.unhexlify(params["tag"])),
+ ),
+ backend,
)
decryptor = cipher.decryptor()
decryptor.authenticate_additional_data(binascii.unhexlify(aad))
@@ -101,7 +123,7 @@
cipher = Cipher(
cipher_factory(binascii.unhexlify(params["key"])),
mode_factory(binascii.unhexlify(params["iv"]), None),
- backend
+ backend,
)
encryptor = cipher.encryptor()
encryptor.authenticate_additional_data(binascii.unhexlify(aad))
@@ -111,10 +133,12 @@
assert binascii.hexlify(encryptor.tag[:tag_len]) == params["tag"]
cipher = Cipher(
cipher_factory(binascii.unhexlify(params["key"])),
- mode_factory(binascii.unhexlify(params["iv"]),
- binascii.unhexlify(params["tag"]),
- min_tag_length=tag_len),
- backend
+ mode_factory(
+ binascii.unhexlify(params["iv"]),
+ binascii.unhexlify(params["tag"]),
+ min_tag_length=tag_len,
+ ),
+ backend,
)
decryptor = cipher.decryptor()
decryptor.authenticate_additional_data(binascii.unhexlify(aad))
@@ -123,13 +147,15 @@
assert actual_plaintext == binascii.unhexlify(plaintext)
-def generate_stream_encryption_test(param_loader, path, file_names,
- cipher_factory):
+def generate_stream_encryption_test(
+ param_loader, path, file_names, cipher_factory
+):
all_params = _load_all_params(path, file_names, param_loader)
@pytest.mark.parametrize("params", all_params)
def test_stream_encryption(self, backend, params):
stream_encryption_test(backend, cipher_factory, params)
+
return test_stream_encryption
@@ -157,6 +183,7 @@
@pytest.mark.parametrize("params", all_params)
def test_hash(self, backend, params):
hash_test(backend, hash_cls, params)
+
return test_hash
@@ -171,6 +198,7 @@
def generate_base_hash_test(algorithm, digest_size):
def test_base_hash(self, backend):
base_hash_test(backend, algorithm, digest_size)
+
return test_base_hash
@@ -191,6 +219,7 @@
def generate_base_hmac_test(hash_cls):
def test_base_hmac(self, backend):
base_hmac_test(backend, hash_cls)
+
return test_base_hmac
@@ -208,6 +237,7 @@
@pytest.mark.parametrize("params", all_params)
def test_hmac(self, backend, params):
hmac_test(backend, algorithm, params)
+
return test_hmac
@@ -224,6 +254,7 @@
@pytest.mark.parametrize("params", all_params)
def test_pbkdf2(self, backend, params):
pbkdf2_test(backend, algorithm, params)
+
return test_pbkdf2
@@ -236,7 +267,7 @@
int(params["length"]),
params["salt"],
int(params["iterations"]),
- backend
+ backend,
)
derived_key = kdf.derive(params["password"])
assert binascii.hexlify(derived_key) == params["derived_key"]
@@ -245,6 +276,7 @@
def generate_aead_exception_test(cipher_factory, mode_factory):
def test_aead_exception(self, backend):
aead_exception_test(backend, cipher_factory, mode_factory)
+
return test_aead_exception
@@ -252,7 +284,7 @@
cipher = Cipher(
cipher_factory(binascii.unhexlify(b"0" * 32)),
mode_factory(binascii.unhexlify(b"0" * 24)),
- backend
+ backend,
)
encryptor = cipher.encryptor()
encryptor.update(b"a" * 16)
@@ -270,7 +302,7 @@
cipher = Cipher(
cipher_factory(binascii.unhexlify(b"0" * 32)),
mode_factory(binascii.unhexlify(b"0" * 24), b"0" * 16),
- backend
+ backend,
)
decryptor = cipher.decryptor()
decryptor.update(b"a" * 16)
@@ -281,6 +313,7 @@
def generate_aead_tag_exception_test(cipher_factory, mode_factory):
def test_aead_tag_exception(self, backend):
aead_tag_exception_test(backend, cipher_factory, mode_factory)
+
return test_aead_tag_exception
@@ -288,7 +321,7 @@
cipher = Cipher(
cipher_factory(binascii.unhexlify(b"0" * 32)),
mode_factory(binascii.unhexlify(b"0" * 24)),
- backend
+ backend,
)
with pytest.raises(ValueError):
@@ -300,7 +333,7 @@
cipher = Cipher(
cipher_factory(binascii.unhexlify(b"0" * 32)),
mode_factory(binascii.unhexlify(b"0" * 24), b"0" * 16),
- backend
+ backend,
)
with pytest.raises(ValueError):
cipher.encryptor()
@@ -312,7 +345,7 @@
int(params["l"]),
salt=binascii.unhexlify(params["salt"]) or None,
info=binascii.unhexlify(params["info"]) or None,
- backend=backend
+ backend=backend,
)
okm = hkdf.derive(binascii.unhexlify(params["ikm"]))
@@ -326,7 +359,7 @@
int(params["l"]),
salt=binascii.unhexlify(params["salt"]) or None,
info=binascii.unhexlify(params["info"]) or None,
- backend=backend
+ backend=backend,
)
prk = hkdf._extract(binascii.unhexlify(params["ikm"]))
@@ -339,7 +372,7 @@
algorithm,
int(params["l"]),
info=binascii.unhexlify(params["info"]) or None,
- backend=backend
+ backend=backend,
)
okm = hkdf.derive(binascii.unhexlify(params["prk"]))
@@ -353,8 +386,7 @@
all_tests = [hkdf_extract_test, hkdf_expand_test, hkdf_derive_test]
@pytest.mark.parametrize(
- ("params", "hkdf_test"),
- itertools.product(all_params, all_tests)
+ ("params", "hkdf_test"), itertools.product(all_params, all_tests)
)
def test_hkdf(self, backend, params, hkdf_test):
hkdf_test(backend, algorithm, params)
@@ -368,16 +400,17 @@
@pytest.mark.parametrize("params", all_params)
def test_kbkdf(self, backend, params):
kbkdf_counter_mode_test(backend, params)
+
return test_kbkdf
def kbkdf_counter_mode_test(backend, params):
supported_algorithms = {
- 'hmac_sha1': hashes.SHA1,
- 'hmac_sha224': hashes.SHA224,
- 'hmac_sha256': hashes.SHA256,
- 'hmac_sha384': hashes.SHA384,
- 'hmac_sha512': hashes.SHA512,
+ "hmac_sha1": hashes.SHA1,
+ "hmac_sha224": hashes.SHA224,
+ "hmac_sha256": hashes.SHA256,
+ "hmac_sha384": hashes.SHA384,
+ "hmac_sha512": hashes.SHA512,
}
supported_counter_locations = {
@@ -385,39 +418,44 @@
"after_fixed": CounterLocation.AfterFixed,
}
- algorithm = supported_algorithms.get(params.get('prf'))
+ algorithm = supported_algorithms.get(params.get("prf"))
if algorithm is None or not backend.hmac_supported(algorithm()):
- pytest.skip("KBKDF does not support algorithm: {0}".format(
- params.get('prf')
- ))
+ pytest.skip(
+ "KBKDF does not support algorithm: {}".format(params.get("prf"))
+ )
ctr_loc = supported_counter_locations.get(params.get("ctrlocation"))
if ctr_loc is None or not isinstance(ctr_loc, CounterLocation):
- pytest.skip("Does not support counter location: {0}".format(
- params.get('ctrlocation')
- ))
+ pytest.skip(
+ "Does not support counter location: {}".format(
+ params.get("ctrlocation")
+ )
+ )
ctrkdf = KBKDFHMAC(
algorithm(),
Mode.CounterMode,
- params['l'] // 8,
- params['rlen'] // 8,
+ params["l"] // 8,
+ params["rlen"] // 8,
None,
ctr_loc,
None,
None,
- binascii.unhexlify(params['fixedinputdata']),
- backend=backend)
+ binascii.unhexlify(params["fixedinputdata"]),
+ backend=backend,
+ )
- ko = ctrkdf.derive(binascii.unhexlify(params['ki']))
+ ko = ctrkdf.derive(binascii.unhexlify(params["ki"]))
assert binascii.hexlify(ko) == params["ko"]
-def generate_rsa_verification_test(param_loader, path, file_names, hash_alg,
- pad_factory):
+def generate_rsa_verification_test(
+ param_loader, path, file_names, hash_alg, pad_factory
+):
all_params = _load_all_params(path, file_names, param_loader)
- all_params = [i for i in all_params
- if i["algorithm"] == hash_alg.name.upper()]
+ all_params = [
+ i for i in all_params if i["algorithm"] == hash_alg.name.upper()
+ ]
@pytest.mark.parametrize("params", all_params)
def test_rsa_verification(self, backend, params):
@@ -428,8 +466,7 @@
def rsa_verification_test(backend, params, hash_alg, pad_factory):
public_numbers = rsa.RSAPublicNumbers(
- e=params["public_exponent"],
- n=params["modulus"]
+ e=params["public_exponent"], n=params["modulus"]
)
public_key = public_numbers.public_key(backend)
pad = pad_factory(params, hash_alg)
@@ -437,19 +474,9 @@
msg = binascii.unhexlify(params["msg"])
if params["fail"]:
with pytest.raises(InvalidSignature):
- public_key.verify(
- signature,
- msg,
- pad,
- hash_alg
- )
+ public_key.verify(signature, msg, pad, hash_alg)
else:
- public_key.verify(
- signature,
- msg,
- pad,
- hash_alg
- )
+ public_key.verify(signature, msg, pad, hash_alg)
def _check_rsa_private_numbers(skey):
@@ -470,3 +497,13 @@
pkey = skey.public_numbers
params = pkey.parameter_numbers
assert pow(params.g, skey.x, params.p) == pkey.y
+
+
+def skip_fips_traditional_openssl(backend, fmt):
+ if (
+ fmt is serialization.PrivateFormat.TraditionalOpenSSL
+ and backend._fips_enabled
+ ):
+ pytest.skip(
+ "Traditional OpenSSL key format is not supported in FIPS mode."
+ )