在服务器(PHP代码)上,我们有两种加密/解密facebook id的方法,如下所示:
private function encryptFacebookId($text)
{
$method = "AES-256-CBC";
$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = openssl_encrypt($text, $method, $this->_cryptKey, 0, $iv);
return base64_encode($iv . $encrypted);
}
public function decryptFacebookId($text)
{
$text = base64_decode($text);
$method = "AES-256-CBC";
$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = substr($text, 0, $iv_size);
$decrypted = openssl_decrypt(substr($text, $iv_size), $method, $this->_cryptKey, 0, $iv);
return $decrypted;
}
使用_cryptKey =" 1231238912389123asdasdklasdkjasd";
在服务器上具有相同的输入和输出值即可。但是当我通过HTTP请求(REST)连接到服务器作为客户端(Android / Java)时。 我尝试在方法" encryptFacebookId($ text)"中将PHP代码的方法转换为Java代码。并将加密文本发送到服务器,但服务器上的方法decryptFacebookId($ text)的结果与客户端的值不同。
这是我在客户端的代码
String facebookId = "123456789";
String keyCrypt = "1231238912389123asdasdklasdkjasd";
try {
SecretKeySpec skeySpec = new SecretKeySpec(keyCrypt.getBytes(),
"AES");
Cipher enCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] ivData = new byte[enCipher.getBlockSize()];
IvParameterSpec iv = new IvParameterSpec(ivData);
enCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encryptedBytes = enCipher.doFinal(facebookId.getBytes());
String ivEncrypted = new String(ivData)
+ new String(encryptedBytes);
String strEncode = Base64
.encodeBase64String(ivEncrypted.getBytes());
System.out.println(strEncode);
} catch (Exception e) {
System.out.println(e.getMessage());
}
请帮我找到正确的方法。
答案 0 :(得分:0)
1)如果你想连续二进制byte []不要将它转换为String使用,例如:
public static byte[] concat(byte[]... args)
{
int fulllength = 0;
for (byte[] arrItem : args) {
fulllength += arrItem.length;
}
byte[] outArray = new byte[fulllength];
int start = 0;
for (byte[] arrItem : args) {
System.arraycopy(arrItem, 0, outArray, start, arrItem.length);
start += arrItem.length;
}
return outArray;
}
byte [] ivEncrypted = concat(ivData,encryptedBytes);
2)您必须确保Base64编码器兼容。