Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_crypt_providers/_cryptography.py: 2%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

110 statements  

1# Copyright (c) 2023, exiledkingcc 

2# All rights reserved. 

3# 

4# Redistribution and use in source and binary forms, with or without 

5# modification, are permitted provided that the following conditions are 

6# met: 

7# 

8# * Redistributions of source code must retain the above copyright notice, 

9# this list of conditions and the following disclaimer. 

10# * Redistributions in binary form must reproduce the above copyright notice, 

11# this list of conditions and the following disclaimer in the documentation 

12# and/or other materials provided with the distribution. 

13# * The name of the author may not be used to endorse or promote products 

14# derived from this software without specific prior written permission. 

15# 

16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 

17# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 

18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 

19# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 

20# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 

21# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 

22# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 

23# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 

24# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 

25# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 

26# POSSIBILITY OF SUCH DAMAGE. 

27 

28import secrets 

29 

30from cryptography import __version__ 

31from cryptography.exceptions import UnsupportedAlgorithm 

32from cryptography.hazmat.decrepit.ciphers.algorithms import ARC4 

33from cryptography.hazmat.primitives.ciphers.algorithms import AES 

34from cryptography.hazmat.primitives.ciphers.base import Cipher 

35from cryptography.hazmat.primitives.ciphers.modes import CBC, ECB 

36from cryptography.hazmat.primitives.padding import PKCS7 

37 

38from pypdf._crypt_providers._base import CryptBase 

39from pypdf._utils import logger_warning 

40from pypdf.errors import PdfStreamError 

41 

42crypt_provider = ("cryptography", __version__) 

43 

44 

45class CryptRC4(CryptBase): 

46 # Assume OpenSSL provides RC4; flipped to False the first time it rejects 

47 # the cipher (e.g. legacy provider disabled), so the failing attempt is 

48 # paid once. 

49 _is_rc4_supported = True 

50 

51 def __init__(self, key: bytes) -> None: 

52 self._key = key 

53 self._fallback = None 

54 if CryptRC4._is_rc4_supported: 

55 self.cipher = Cipher(ARC4(key), mode=None) 

56 else: 

57 self._fallback = self._pure_python_rc4(key) 

58 

59 @staticmethod 

60 def _pure_python_rc4(key: bytes) -> CryptBase: 

61 from pypdf._crypt_providers import _fallback # noqa: PLC0415 

62 

63 return _fallback.CryptRC4(key) 

64 

65 @classmethod 

66 def _disable_rc4(cls, key: bytes) -> CryptBase: 

67 if cls._is_rc4_supported: 

68 logger_warning( 

69 ( 

70 "RC4 is not supported by the current OpenSSL build; " 

71 "falling back to the pure-Python RC4 implementation." 

72 ), 

73 source=__name__, 

74 ) 

75 cls._is_rc4_supported = False 

76 return cls._pure_python_rc4(key) 

77 

78 def encrypt(self, data: bytes) -> bytes: 

79 if self._fallback is not None: 

80 return self._fallback.encrypt(data) 

81 try: 

82 encryptor = self.cipher.encryptor() 

83 return encryptor.update(data) + encryptor.finalize() 

84 except UnsupportedAlgorithm: 

85 self._fallback = self._disable_rc4(self._key) 

86 return self._fallback.encrypt(data) 

87 

88 def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: 

89 if self._fallback is not None: 

90 return self._fallback.decrypt(data, strict=strict) 

91 try: 

92 decryptor = self.cipher.decryptor() 

93 return decryptor.update(data) + decryptor.finalize() 

94 except UnsupportedAlgorithm: 

95 self._fallback = self._disable_rc4(self._key) 

96 return self._fallback.decrypt(data, strict=strict) 

97 

98 

99class CryptAES(CryptBase): 

100 def __init__(self, key: bytes) -> None: 

101 self.alg = AES(key) 

102 

103 def encrypt(self, data: bytes) -> bytes: 

104 iv = secrets.token_bytes(16) 

105 padder = PKCS7(128).padder() 

106 padded_data = padder.update(data) + padder.finalize() 

107 

108 cipher = Cipher(self.alg, CBC(iv)) 

109 encryptor = cipher.encryptor() 

110 return iv + encryptor.update(padded_data) + encryptor.finalize() 

111 

112 def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: 

113 iv = data[:16] 

114 data = data[16:] 

115 # for empty encrypted data 

116 if not data: 

117 return data 

118 

119 if not strict and len(data) % 16 != 0: 

120 logger_warning("Adding missing padding.", source=__name__) 

121 padder = PKCS7(128).padder() 

122 data = padder.update(data) + padder.finalize() 

123 

124 cipher = Cipher(self.alg, CBC(iv)) 

125 decryptor = cipher.decryptor() 

126 try: 

127 padded_data = decryptor.update(data) + decryptor.finalize() 

128 except ValueError as exception: 

129 # Only raised in strict mode. Non-strict mode fixes padding. 

130 raise PdfStreamError(exception) from exception 

131 

132 unpadder = PKCS7(128).unpadder() 

133 try: 

134 return unpadder.update(padded_data) + unpadder.finalize() 

135 except ValueError as exception: 

136 if strict: 

137 raise PdfStreamError(exception) from exception 

138 logger_warning("Ignoring padding error: %(exception)s", source=__name__, exception=exception) 

139 return padded_data[: -padded_data[-1]] 

140 

141 

142def rc4_encrypt(key: bytes, data: bytes) -> bytes: 

143 if CryptRC4._is_rc4_supported: 

144 try: 

145 encryptor = Cipher(ARC4(key), mode=None).encryptor() 

146 return encryptor.update(data) + encryptor.finalize() 

147 except UnsupportedAlgorithm: 

148 return CryptRC4._disable_rc4(key).encrypt(data) 

149 return CryptRC4._pure_python_rc4(key).encrypt(data) 

150 

151 

152def rc4_decrypt(key: bytes, data: bytes) -> bytes: 

153 if CryptRC4._is_rc4_supported: 

154 try: 

155 decryptor = Cipher(ARC4(key), mode=None).decryptor() 

156 return decryptor.update(data) + decryptor.finalize() 

157 except UnsupportedAlgorithm: 

158 return CryptRC4._disable_rc4(key).decrypt(data) 

159 return CryptRC4._pure_python_rc4(key).decrypt(data) 

160 

161 

162def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes: 

163 encryptor = Cipher(AES(key), mode=ECB()).encryptor() 

164 return encryptor.update(data) + encryptor.finalize() 

165 

166 

167def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes: 

168 decryptor = Cipher(AES(key), mode=ECB()).decryptor() 

169 return decryptor.update(data) + decryptor.finalize() 

170 

171 

172def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes: 

173 encryptor = Cipher(AES(key), mode=CBC(iv)).encryptor() 

174 return encryptor.update(data) + encryptor.finalize() 

175 

176 

177def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes: 

178 decryptor = Cipher(AES(key), mode=CBC(iv)).decryptor() 

179 return decryptor.update(data) + decryptor.finalize()