这种模式适合中小型系统,开发成本低,易于调试和部署。
修改后的 __init__ 方法如下:class AESCipher(object): def __init__(self, key=None): # Initialize the AESCipher object with a key, # defaulting to a randomly generated key self.block_size = AES.block_size if key: self.key = b64decode(key.encode()) else: self.key = Random.new().read(self.block_size)完整代码示例 以下是修改后的完整代码示例:import hashlib from Crypto.Cipher import AES from Crypto import Random from base64 import b64encode, b64decode class AESCipher(object): def __init__(self, key=None): # Initialize the AESCipher object with a key, # defaulting to a randomly generated key self.block_size = AES.block_size if key: self.key = b64decode(key.encode()) else: self.key = Random.new().read(self.block_size) def encrypt(self, plain_text): # Encrypt the provided plaintext using AES in CBC mode plain_text = self.__pad(plain_text) iv = Random.new().read(self.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) encrypted_text = cipher.encrypt(plain_text) # Combine IV and encrypted text, then base64 encode for safe representation return b64encode(iv + encrypted_text).decode("utf-8") def decrypt(self, encrypted_text): # Decrypt the provided ciphertext using AES in CBC mode encrypted_text = b64decode(encrypted_text) iv = encrypted_text[:self.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) plain_text = cipher.decrypt(encrypted_text[self.block_size:]) return self.__unpad(plain_text) def get_key(self): # Get the base64 encoded representation of the key return b64encode(self.key).decode("utf-8") def __pad(self, plain_text): # Add PKCS7 padding to the plaintext number_of_bytes_to_pad = self.block_size - len(plain_text) % self.block_size padding_bytes = bytes([number_of_bytes_to_pad] * number_of_bytes_to_pad) padded_plain_text = plain_text.encode() + padding_bytes return padded_plain_text @staticmethod def __unpad(plain_text): # Remove PKCS7 padding from the plaintext last_byte = plain_text[-1] return plain_text[:-last_byte] if isinstance(last_byte, int) else plain_text def save_to_notepad(text, key, filename): # Save encrypted text and key to a file with open(filename, 'w') as file: file.write(f"Key: {key}\nEncrypted text: {text}") print(f"Text and key saved to {filename}") def encrypt_and_save(): # Take user input, encrypt, and save to a file user_input = "" while not user_input: user_input = input("Enter the plaintext: ") aes_cipher = AESCipher() # Randomly generated key encrypted_text = aes_cipher.encrypt(user_input) key = aes_cipher.get_key() filename = input("Enter the filename (including .txt extension): ") save_to_notepad(encrypted_text, key, filename) def decrypt_from_file(): # Decrypt encrypted text from a file using a key filename = input("Enter the filename to decrypt (including .txt extension): ") with open(filename, 'r') as file: lines = file.readlines() key = lines[0].split(":")[1].strip() encrypted_text = lines[1].split(":")[1].strip() aes_cipher = AESCipher(key) decrypted_bytes = aes_cipher.decrypt(encrypted_text) # Decoding only if the decrypted bytes are not empty decrypted_text = decrypted_bytes.decode("utf-8") if decrypted_bytes else "" print("Decrypted Text:", decrypted_text) def encrypt_and_decrypt_in_command_line(): # Encrypt and then decrypt user input in the command line user_input = "" while not user_input: user_input = input("Enter the plaintext: ") aes_cipher = AESCipher() encrypted_text = aes_cipher.encrypt(user_input) key = aes_cipher.get_key() print("Key:", key) print("Encrypted Text:", encrypted_text) decrypted_bytes = aes_cipher.decrypt(encrypted_text) decrypted_text = decrypted_bytes.decode("utf-8") if decrypted_bytes else "" print("Decrypted Text:", decrypted_text) # Menu Interface while True: print("\nMenu:") print("1. Encrypt and save to file") print("2. Decrypt from file") print("3. Encrypt and decrypt in command line") print("4. Exit") choice = input("Enter your choice (1, 2, 3, or 4): ") if choice == '1': encrypt_and_save() elif choice == '2': decrypt_from_file() elif choice == '3': encrypt_and_decrypt_in_command_line() elif choice == '4': print("Exiting the program. Goodbye!") break else: print("Invalid choice. Please enter 1, 2, 3, or 4.")注意事项 密钥管理: 密钥的安全至关重要。
本文旨在讲解如何在 Laravel 应用中,根据用户的本地化设置(locale)发送定制化的通知。
本文将指导你如何正确配置 OpenCV 和 Elgato Camera Hub,从而顺利地使用手机摄像头。
func calculateValue(input int) (result int) { result = input * 2 // 赋值给命名返回值参数 'result' if input < 0 { result := 0 // 声明了一个新的局部变量 'result',遮蔽了命名返回值参数 fmt.Printf("内部作用域:局部 result = %d\n", result) // 输出:0 // 此时对 'result' 的赋值操作会作用于局部变量 // result = 10 // 如果执行这行,会改变局部变量 'result' return // 这里执行的是裸返回,它会返回命名返回值参数 'result' 的值 (input * 2),而不是局部变量 'result' 的值 (0 或 10) } return // 返回命名返回值参数 'result' 的值 } // 调用示例: // fmt.Println(calculateValue(5)) // 输出:10 // fmt.Println(calculateValue(-3)) // 输出:-6 (而不是0或10)这种行为非常容易引起混淆和错误,因此在使用命名返回值参数时,应尽量避免在函数内部声明同名局部变量。
在Go语言中,获取接口的reflect.Type,最常用的方法是 reflect.TypeOf((*someInterface)(nil)).Elem()。
转义问题:当PHP输出JavaScript字符串时,需要特别注意字符串中的引号和特殊字符转义。
Go结构体是复合数据类型,用于组合不同字段构建数据模型;2. 通过type定义结构体,字段首字母大写可导出,小写则包内私有;3. 实例化支持字段名初始化、顺序赋值、逐字段赋值和new创建指针;4. 字段访问用点运算符,指针亦可直接使用点操作。
要解决这个问题,PHP 提供了专门的自然排序函数。
下面介绍一种基于gRPC的常见实现方式。
底层数组不释放: 底层数组的内存并不会被垃圾回收器回收,除非所有引用它的Slice都超出作用域。
在Go语言中,指针类型和值类型是两种基础的数据处理方式,理解它们的区别对编写高效、安全的代码至关重要。
记住,良好的错误处理、异步处理和正确的路径管理是构建健壮图片处理系统的关键。
然而,当方法返回后,原始切片 ms 的长度仍然是3,并且出现了重复的最后一个元素。
定义一个升级器(Upgrader),处理HTTP协议切换。
使用context.WithTimeout和context.WithCancel可有效实现超时与取消控制;2. 发起HTTP或数据库请求时应设置超时,避免阻塞导致资源耗尽;3. HTTP处理器中通过r.Context()传递请求上下文,确保下游操作能级联取消;4. 多层调用中传播context,使整个调用链响应统一取消信号;5. 主动取消场景可用context.WithCancel手动触发,协程监听ctx.Done()及时退出;6. 每次创建context都需调用cancel防止泄漏。
TCP/IP协议栈在处理大量并发连接时,也可能因为其内部缓冲区、连接状态管理等机制而成为瓶颈。
C++中处理UTF-8需理解Unicode编码原理,使用std::string存储UTF-8文本,但操作时区分字节与字符;推荐用utf8cpp或ICU库安全遍历、转换编码,避免手动解析错误。
可读性直接影响可维护性 代码的首要读者是开发者,而不是机器。
C++中创建目录推荐使用C++17的<filesystem>库实现跨平台操作,如std::filesystem::create_directory()创建单层目录,create_directories()递归创建多级目录;Windows可调用CreateDirectoryA(),Linux/Unix使用mkdir()函数,但优先选用<filesystem>以简化开发并确保兼容性。
本文链接:http://www.theyalibrarian.com/32444_4037b.html