我已经阅读了以下主题,它们有所帮助,但我正在寻找更多信息。
如何使用 BlackBerry 的初始化向量参数编写 AES/CBC/PKCS5Padding 加密和解密
基本上,我正在编写一个程序,该程序将加密通过 TCP/IP 发送的请求,然后由服务器程序解密。加密需要是 AES,做一些研究我发现我需要使用 CBC 和 PKCS5Padding。所以基本上我还需要一个密钥和一个 IV。
我正在开发的应用程序是用于手机的,所以我想使用 java 安全包来减小大小。我已经完成了设计,但不确定 IV 和共享密钥的实现。
这是一些代码:
// My user name
byte[] loginId = "login".getBytes();
byte[] preSharedKey128 = "ACME-1234AC".getBytes();
byte[] preSharedKey192 = "ACME-1234ACME-1234A".getBytes();
// 256 bit key
byte[] preSharedKey256 = "ACME-1234ACME-1234ACME-1234".getBytes();
byte[] preSharedKey = preSharedKey256;
// Initialization Vector
// Required for CBC
byte[] iv ={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
IvParameterSpec ips = new IvParameterSpec(iv);
byte[] encodedKey = new byte[loginId.length + preSharedKey.length];
System.arraycopy(loginId, 0, encodedKey, 0, loginId.length);
System.arraycopy(preSharedKey, 0, encodedKey, loginId.length, preSharedKey.length);
// The SecretKeySpec provides a mechanism for application-specific generation
// of cryptography keys for consumption by the Java Crypto classes.
// Create a key specification first, based on our key input.
SecretKey aesKey = new SecretKeySpec(encodedKey, "AES");
// Create a Cipher for encrypting the data using the key we created.
Cipher encryptCipher;
encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Initialize the Cipher with key and parameters
encryptCipher.init(Cipher.ENCRYPT_MODE, aesKey, ips);
// Our cleartext
String clearString = "33,8244000,9999,411,5012022517,0.00,0,1,V330";
byte[] cleartext = clearString.getBytes();
// Encrypt the cleartext
byte[] ciphertext = encryptCipher.doFinal(cleartext);
// Now decrypt back again...
// Decryption cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Initialize PBE Cipher with key and parameters
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ips);
// Decrypt the cleartext
byte[] deciphertext = decryptCipher.doFinal(ciphertext);
简而言之,它应该做的是加密一些可以由服务器解密的消息,而服务器不需要从电话中获取密钥或 IV。有没有一种方法可以做到这一点,我可以保护手机上的 IV 和密钥,并且仍然拥有服务器知道的密钥和 IV?如果不是,请随时告诉我让事情更清楚。