Class representing AES key object.
| 95 | |
| 96 | |
| 97 | class AESKey(object): |
| 98 | """ |
| 99 | Class representing AES key object. |
| 100 | """ |
| 101 | |
| 102 | aes_key_string = None |
| 103 | hmac_key_string = None |
| 104 | hmac_key_size = None |
| 105 | mode = None |
| 106 | size = None |
| 107 | |
| 108 | def __init__( |
| 109 | self, |
| 110 | aes_key_string, |
| 111 | hmac_key_string, |
| 112 | hmac_key_size, |
| 113 | mode="CBC", |
| 114 | size=DEFAULT_AES_KEY_SIZE, |
| 115 | ): |
| 116 | if mode not in ["CBC"]: |
| 117 | raise ValueError("Unsupported mode: %s" % (mode)) |
| 118 | |
| 119 | if size < MINIMUM_AES_KEY_SIZE: |
| 120 | raise ValueError("Unsafe key size: %s" % (size)) |
| 121 | |
| 122 | self.aes_key_string = aes_key_string |
| 123 | self.hmac_key_string = hmac_key_string |
| 124 | self.hmac_key_size = int(hmac_key_size) |
| 125 | self.mode = mode.upper() |
| 126 | self.size = int(size) |
| 127 | |
| 128 | # We also store bytes version of the key since bytes are needed by encrypt and decrypt |
| 129 | # methods |
| 130 | self.hmac_key_bytes = Base64WSDecode(self.hmac_key_string) |
| 131 | self.aes_key_bytes = Base64WSDecode(self.aes_key_string) |
| 132 | |
| 133 | @classmethod |
| 134 | def generate(self, key_size=DEFAULT_AES_KEY_SIZE): |
| 135 | """ |
| 136 | Generate a new AES key with the corresponding HMAC key. |
| 137 | |
| 138 | :rtype: :class:`AESKey` |
| 139 | """ |
| 140 | if key_size < MINIMUM_AES_KEY_SIZE: |
| 141 | raise ValueError("Unsafe key size: %s" % (key_size)) |
| 142 | |
| 143 | aes_key_bytes = os.urandom(int(key_size / 8)) |
| 144 | aes_key_string = Base64WSEncode(aes_key_bytes) |
| 145 | |
| 146 | hmac_key_bytes = os.urandom(int(key_size / 8)) |
| 147 | hmac_key_string = Base64WSEncode(hmac_key_bytes) |
| 148 | |
| 149 | return AESKey( |
| 150 | aes_key_string=aes_key_string, |
| 151 | hmac_key_string=hmac_key_string, |
| 152 | hmac_key_size=key_size, |
| 153 | mode="CBC", |
| 154 | size=key_size, |
no outgoing calls
no test coverage detected