Class SecretBox
java.lang.Object
cloud.opencode.base.crypto.sealedbox.SecretBox
Secret Box - Simplified symmetric encryption (NaCl/Libsodium style)
秘密盒 - 简化的对称加密(NaCl/Libsodium 风格)
Provides a simple interface for authenticated symmetric encryption using AES-GCM. The nonce is automatically generated and prepended to the ciphertext.
使用 AES-GCM 提供简单的认证对称加密接口。 随机数自动生成并添加到密文前面。
Features | 主要功能:
- Authenticated encryption - 认证加密
- Automatic nonce generation - 自动随机数生成
- Simple API - 简单 API
- 256-bit AES-GCM - 256位 AES-GCM
Usage Examples | 使用示例:
// Generate a key
SecretKey key = SecretBox.generateKey();
// Encrypt
byte[] message = "Secret message".getBytes();
byte[] encrypted = SecretBox.encrypt(message, key);
// Decrypt
byte[] decrypted = SecretBox.decrypt(encrypted, key);
// With string convenience methods
String encrypted = SecretBox.encryptString("Hello", key);
String decrypted = SecretBox.decryptString(encrypted, key);
Security | 安全性:
- Thread-safe: Yes - 线程安全: 是
- Null-safe: Yes - 空值安全: 是
- Since:
- JDK 25, opencode-base-crypto V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic byte[]Decrypts a message.static StringdecryptAsString(byte[] encrypted, SecretKey key) Decrypts a message and returns as string.static byte[]decryptWithAad(byte[] encrypted, SecretKey key, byte[] aad) Decrypts with additional authenticated data (AAD).static byte[]Encrypts a message.static byte[]Encrypts a string message.static byte[]encryptWithAad(byte[] plaintext, SecretKey key, byte[] aad) Encrypts with additional authenticated data (AAD).static SecretKeyGenerates a new 256-bit secret key.static SecretKeykeyFromBytes(byte[] keyBytes) Creates a secret key from raw bytes.
-
Method Details
-
generateKey
Generates a new 256-bit secret key. 生成新的 256 位密钥。- Returns:
- the secret key - 密钥
-
keyFromBytes
Creates a secret key from raw bytes. 从原始字节创建密钥。- Parameters:
keyBytes- the key bytes (must be 32 bytes) - 密钥字节(必须是 32 字节)- Returns:
- the secret key - 密钥
-
encrypt
Encrypts a message. 加密消息。- Parameters:
plaintext- the message to encrypt - 要加密的消息key- the secret key - 密钥- Returns:
- the encrypted message (nonce + ciphertext) - 加密的消息(随机数 + 密文)
-
encrypt
-
encryptWithAad
Encrypts with additional authenticated data (AAD). 使用附加认证数据(AAD)加密。- Parameters:
plaintext- the message to encrypt - 要加密的消息key- the secret key - 密钥aad- additional authenticated data - 附加认证数据- Returns:
- the encrypted message - 加密的消息
-
decrypt
Decrypts a message. 解密消息。- Parameters:
encrypted- the encrypted message (nonce + ciphertext) - 加密的消息key- the secret key - 密钥- Returns:
- the decrypted message - 解密的消息
-
decryptAsString
-
decryptWithAad
Decrypts with additional authenticated data (AAD). 使用附加认证数据(AAD)解密。- Parameters:
encrypted- the encrypted message - 加密的消息key- the secret key - 密钥aad- additional authenticated data - 附加认证数据- Returns:
- the decrypted message - 解密的消息
-