Add object detection, tracking, mobile notifications, and search to any security camera.
trim aes
roryclear1a52f185b79e
diff --git a/experimental/aes.py b/experimental/aes.pyindex c6e8bc0..2f56ca4 100644--- a/experimental/aes.py+++ b/experimental/aes.py@@ -54,22 +54,12 @@import copyimport struct-__all__ = ["AES", "AESModeOfOperationCTR", "AESModeOfOperationCBC", "AESModeOfOperationCFB",- "AESModeOfOperationECB", "AESModeOfOperationOFB", "AESModesOfOperation", "Counter"]+__all__ = ["AES"]def _compact_word(word):return (word[0] << 24) | (word[1] << 16) | (word[2] << 8) | word[3]-def _string_to_bytes(text):- return list(ord(c) for c in text)--def _bytes_to_string(binary):- return "".join(chr(b) for b in binary)--def _concat_list(a, b):- return a + b-# Python 3 compatibilitytry:@@ -77,21 +67,6 @@ try:except Exception:xrange = range- # Python 3 supports bytes, which is already an array of integers- def _string_to_bytes(text):- if isinstance(text, bytes):- return text- return [ord(c) for c in text]-- # In Python 3, we return bytes- def _bytes_to_string(binary):- return bytes(binary)-- # Python 3 cannot concatenate a list onto a bytes, so we bytes-ify it first- def _concat_list(a, b):- return a + bytes(b)--# Based *largely* on the Rijndael implementation# See: http://csrc.nist.gov/publications/fips/fips197/fips-197.pdfclass AES(object):@@ -232,358 +207,4 @@ class AES(object):result.append((self.S[(t[(i + s2) % 4] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF)result.append((self.S[ t[(i + s3) % 4] & 0xFF] ^ tt ) & 0xFF)- return result-- def decrypt(self, ciphertext):- 'Decrypt a block of cipher text using the AES block cipher.'-- if len(ciphertext) != 16:- raise ValueError('wrong block length')-- rounds = len(self._Kd) - 1- (s1, s2, s3) = [3, 2, 1]- a = [0, 0, 0, 0]-- # Convert ciphertext to (ints ^ key)- t = [(_compact_word(ciphertext[4 * i:4 * i + 4]) ^ self._Kd[0][i]) for i in xrange(0, 4)]-- # Apply round transforms- for r in xrange(1, rounds):- for i in xrange(0, 4):- a[i] = (self.T5[(t[ i ] >> 24) & 0xFF] ^- self.T6[(t[(i + s1) % 4] >> 16) & 0xFF] ^- self.T7[(t[(i + s2) % 4] >> 8) & 0xFF] ^- self.T8[ t[(i + s3) % 4] & 0xFF] ^- self._Kd[r][i])- t = copy.copy(a)-- # The last round is special- result = [ ]- for i in xrange(0, 4):- tt = self._Kd[rounds][i]- result.append((self.Si[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)- result.append((self.Si[(t[(i + s1) % 4] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)- result.append((self.Si[(t[(i + s2) % 4] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF)- result.append((self.Si[ t[(i + s3) % 4] & 0xFF] ^ tt ) & 0xFF)-- return result---class Counter(object):- '''A counter object for the Counter (CTR) mode of operation.-- To create a custom counter, you can usually just override the- increment method.'''-- def __init__(self, initial_value = 1):-- # Convert the value into an array of bytes long- self._counter = [ ((initial_value >> i) % 256) for i in xrange(128 - 8, -1, -8) ]-- value = property(lambda s: s._counter)-- def increment(self):- '''Increment the counter (overflow rolls back to 0).'''-- for i in xrange(len(self._counter) - 1, -1, -1):- self._counter[i] += 1-- if self._counter[i] < 256: break-- # Carry the one- self._counter[i] = 0-- # Overflow- else:- self._counter = [ 0 ] * len(self._counter)---class AESBlockModeOfOperation(object):- '''Super-class for AES modes of operation that require blocks.'''- def __init__(self, key):- self._aes = AES(key)-- def decrypt(self, ciphertext):- raise Exception('not implemented')-- def encrypt(self, plaintext):- raise Exception('not implemented')---class AESStreamModeOfOperation(AESBlockModeOfOperation):- '''Super-class for AES modes of operation that are stream-ciphers.'''--class AESSegmentModeOfOperation(AESStreamModeOfOperation):- '''Super-class for AES modes of operation that segment data.'''-- segment_bytes = 16----class AESModeOfOperationECB(AESBlockModeOfOperation):- '''AES Electronic Codebook Mode of Operation.-- o Block-cipher, so data must be padded to 16 byte boundaries-- Security Notes:- o This mode is not recommended- o Any two identical blocks produce identical encrypted values,- exposing data patterns. (See the image of Tux on wikipedia)-- Also see:- o https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_.28ECB.29- o See NIST SP800-38A (http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf); section 6.1'''--- name = "Electronic Codebook (ECB)"-- def encrypt(self, plaintext):- if len(plaintext) != 16:- raise ValueError('plaintext block must be 16 bytes')-- plaintext = _string_to_bytes(plaintext)- return _bytes_to_string(self._aes.encrypt(plaintext))-- def decrypt(self, ciphertext):- if len(ciphertext) != 16:- raise ValueError('ciphertext block must be 16 bytes')-- ciphertext = _string_to_bytes(ciphertext)- return _bytes_to_string(self._aes.decrypt(ciphertext))----class AESModeOfOperationCBC(AESBlockModeOfOperation):- '''AES Cipher-Block Chaining Mode of Operation.-- o The Initialization Vector (IV)- o Block-cipher, so data must be padded to 16 byte boundaries- o An incorrect initialization vector will only cause the first- block to be corrupt; all other blocks will be intact- o A corrupt bit in the cipher text will cause a block to be- corrupted, and the next block to be inverted, but all other- blocks will be intact.-- Security Notes:- o This method (and CTR) ARE recommended.-- Also see:- o https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_.28CBC.29- o See NIST SP800-38A (http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf); section 6.2'''--- name = "Cipher-Block Chaining (CBC)"-- def __init__(self, key, iv = None):- if iv is None:- self._last_cipherblock = [ 0 ] * 16- elif len(iv) != 16:- raise ValueError('initialization vector must be 16 bytes')- else:- self._last_cipherblock = _string_to_bytes(iv)-- AESBlockModeOfOperation.__init__(self, key)-- def encrypt(self, plaintext):- if len(plaintext) != 16:- raise ValueError('plaintext block must be 16 bytes')-- plaintext = _string_to_bytes(plaintext)- precipherblock = [ (p ^ l) for (p, l) in zip(plaintext, self._last_cipherblock) ]- self._last_cipherblock = self._aes.encrypt(precipherblock)-- return _bytes_to_string(self._last_cipherblock)-- def decrypt(self, ciphertext):- if len(ciphertext) != 16:- raise ValueError('ciphertext block must be 16 bytes')-- cipherblock = _string_to_bytes(ciphertext)- plaintext = [ (p ^ l) for (p, l) in zip(self._aes.decrypt(cipherblock), self._last_cipherblock) ]- self._last_cipherblock = cipherblock-- return _bytes_to_string(plaintext)----class AESModeOfOperationCFB(AESSegmentModeOfOperation):- '''AES Cipher Feedback Mode of Operation.-- o A stream-cipher, so input does not need to be padded to blocks,- but does need to be padded to segment_size-- Also see:- o https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_feedback_.28CFB.29- o See NIST SP800-38A (http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf); section 6.3'''--- name = "Cipher Feedback (CFB)"-- def __init__(self, key, iv, segment_size = 1):- if segment_size == 0: segment_size = 1-- if iv is None:- self._shift_register = [ 0 ] * 16- elif len(iv) != 16:- raise ValueError('initialization vector must be 16 bytes')- else:- self._shift_register = _string_to_bytes(iv)-- self._segment_bytes = segment_size-- AESBlockModeOfOperation.__init__(self, key)-- segment_bytes = property(lambda s: s._segment_bytes)-- def encrypt(self, plaintext):- if len(plaintext) % self._segment_bytes != 0:- raise ValueError('plaintext block must be a multiple of segment_size')-- plaintext = _string_to_bytes(plaintext)-- # Break block into segments- encrypted = [ ]- for i in xrange(0, len(plaintext), self._segment_bytes):- plaintext_segment = plaintext[i: i + self._segment_bytes]- xor_segment = self._aes.encrypt(self._shift_register)[:len(plaintext_segment)]- cipher_segment = [ (p ^ x) for (p, x) in zip(plaintext_segment, xor_segment) ]-- # Shift the top bits out and the ciphertext in- self._shift_register = _concat_list(self._shift_register[len(cipher_segment):], cipher_segment)-- encrypted.extend(cipher_segment)-- return _bytes_to_string(encrypted)-- def decrypt(self, ciphertext):- if len(ciphertext) % self._segment_bytes != 0:- raise ValueError('ciphertext block must be a multiple of segment_size')-- ciphertext = _string_to_bytes(ciphertext)-- # Break block into segments- decrypted = [ ]- for i in xrange(0, len(ciphertext), self._segment_bytes):- cipher_segment = ciphertext[i: i + self._segment_bytes]- xor_segment = self._aes.encrypt(self._shift_register)[:len(cipher_segment)]- plaintext_segment = [ (p ^ x) for (p, x) in zip(cipher_segment, xor_segment) ]-- # Shift the top bits out and the ciphertext in- self._shift_register = _concat_list(self._shift_register[len(cipher_segment):], cipher_segment)-- decrypted.extend(plaintext_segment)-- return _bytes_to_string(decrypted)----class AESModeOfOperationOFB(AESStreamModeOfOperation):- '''AES Output Feedback Mode of Operation.-- o A stream-cipher, so input does not need to be padded to blocks,- allowing arbitrary length data.- o A bit twiddled in the cipher text, twiddles the same bit in the- same bit in the plain text, which can be useful for error- correction techniques.-- Also see:- o https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_feedback_.28OFB.29- o See NIST SP800-38A (http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf); section 6.4'''--- name = "Output Feedback (OFB)"-- def __init__(self, key, iv = None):- if iv is None:- self._last_precipherblock = [ 0 ] * 16- elif len(iv) != 16:- raise ValueError('initialization vector must be 16 bytes')- else:- self._last_precipherblock = _string_to_bytes(iv)-- self._remaining_block = [ ]-- AESBlockModeOfOperation.__init__(self, key)-- def encrypt(self, plaintext):- encrypted = [ ]- for p in _string_to_bytes(plaintext):- if len(self._remaining_block) == 0:- self._remaining_block = self._aes.encrypt(self._last_precipherblock)- self._last_precipherblock = [ ]- precipherbyte = self._remaining_block.pop(0)- self._last_precipherblock.append(precipherbyte)- cipherbyte = p ^ precipherbyte- encrypted.append(cipherbyte)-- return _bytes_to_string(encrypted)-- def decrypt(self, ciphertext):- # AES-OFB is symetric- return self.encrypt(ciphertext)----class AESModeOfOperationCTR(AESStreamModeOfOperation):- '''AES Counter Mode of Operation.-- o A stream-cipher, so input does not need to be padded to blocks,- allowing arbitrary length data.- o The counter must be the same size as the key size (ie. len(key))- o Each block independant of the other, so a corrupt byte will not- damage future blocks.- o Each block has a uniue counter value associated with it, which- contributes to the encrypted value, so no data patterns are- leaked.- o Also known as: Counter Mode (CM), Integer Counter Mode (ICM) and- Segmented Integer Counter (SIC-- Security Notes:- o This method (and CBC) ARE recommended.- o Each message block is associated with a counter value which must be- unique for ALL messages with the same key. Otherwise security may be- compromised.-- Also see:-- o https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29- o See NIST SP800-38A (http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf); section 6.5- and Appendix B for managing the initial counter'''--- name = "Counter (CTR)"-- def __init__(self, key, counter = None):- AESBlockModeOfOperation.__init__(self, key)-- if counter is None:- counter = Counter()-- self._counter = counter- self._remaining_counter = [ ]-- def encrypt(self, plaintext):- while len(self._remaining_counter) < len(plaintext):- self._remaining_counter += self._aes.encrypt(self._counter.value)- self._counter.increment()-- plaintext = _string_to_bytes(plaintext)-- encrypted = [ (p ^ c) for (p, c) in zip(plaintext, self._remaining_counter) ]- self._remaining_counter = self._remaining_counter[len(encrypted):]-- return _bytes_to_string(encrypted)-- def decrypt(self, crypttext):- # AES-CTR is symetric- return self.encrypt(crypttext)---# Simple lookup table for each mode-AESModesOfOperation = dict(- ctr = AESModeOfOperationCTR,- cbc = AESModeOfOperationCBC,- cfb = AESModeOfOperationCFB,- ecb = AESModeOfOperationECB,- ofb = AESModeOfOperationOFB,-)+ return result\ No newline at end of filediff --git a/experimental/clearcam_rtsp.py b/experimental/clearcam_rtsp.pyindex 49ff583..7f8befd 100644--- a/experimental/clearcam_rtsp.py+++ b/experimental/clearcam_rtsp.py@@ -455,7 +455,7 @@ class VideoCapture:cv2.imwrite(filename, self.annotated_frame)if userID is not None: send_notif(userID)last_det = time.time()- if (send_det and userID is not None) and time.time() - last_det >= 8: #send 15ish second clip after+ if (send_det and userID is not None) and time.time() - last_det >= 15: #send 15ish second clip afteros.makedirs("event_clips", exist_ok=True)mp4_filename = f"event_clips/{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.mp4"self.streamer.export_last_segments(Path(mp4_filename))