我在我的 Php WebSerice 中使用此代码来加密和解密数据:
<?php
/**
* Class that will deal with the encryption of the api
*/
class Encryption
{
private $KEY = "some key"; //the encryption key
/**
* Encrypt data
* @param $data string the data to encrypt
* @return string the encrypted data
*/
public function encrypt($data)
{
if (!empty($data))
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->KEY, $data, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
/**
* Decrypt data
* @param $data string the data to decrypt
* @return string the decrypted data
*/
public function decrypt($data)
{
if (!empty($data))
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->KEY, base64_decode($data), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
}
?>
在我的 Android 应用程序中,这是我的加密方法:
/**
* api encryption key
*/
private static final String KEY = Base64.encodeBytes("some key".getBytes());
/**
* api's encryption algorithm
*/
private static final String ALGOITHM = "AES/CBC/PKCS5Padding";
/**
* Encrypt a data string
* @param data the data string
* @return an encrypted string
* @throws Exception when encryption failed
*/
public static String encrypt(String data) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(), ALGOITHM);
Cipher cipher = Cipher.getInstance(ALGOITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] dataBytes = data.getBytes(););
byte[] encryptedBytes = cipher.doFinal(dataBytes);
return Base64.encodeBytes(encryptedBytes);
}
但数据显示不正确......有什么想法吗?