使用Android和PHP加密/解密
问题描述:
对不起,这个问题。我已阅读所有以前的问题,但我的代码仍然无法正常工作。 在此先感谢任何能够帮助我理解问题出在哪里的人。使用Android和PHP加密/解密
在Android中我使用此代码用于读取公钥并产生密文:
public static PublicKey getPublicKeyFromString(String stringKey) throws Exception {
byte[] keyBytes = stringKey.getBytes();
byte[] decode = Base64.decode(keyBytes, Base64.DEFAULT);
KeyFactory fact = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(decode);
return (PublicKey) fact.generatePublic(x509KeySpec);
}
public static String RSAEncrypt(final String plain, final PublicKey publicKey)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] encryptedBytes;
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}
//I call these functions in this manner.
private final String pubKeyString =
//"-----BEGIN PUBLIC KEY-----" +
"MIG..." +
"...";
//"-----END PUBLIC KEY-----"
PublicKey pubKey = RSAFunctions.getPublicKeyFromString(pubKeyString);
String encData = RSAFunctions.RSAEncrypt("prova", pubKey);
的publickey.php和privatekey.php文件在PHP中生成与此代码:
<?php
include('./Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey()); // == $rsa->createKey(1024) where 1024 is the key size
$File1 = "./privatekey.php";
$Handle = fopen($File1, 'w');
fwrite($Handle, "<?php \$privatekey=\"" . $privatekey . "\"?>");
fclose($Handle);
$File2 = "./publickey.php";
$Handle = fopen($File2, 'w');
fwrite($Handle, "<?php \$publickey=\"" . $publickey . "\"?>");
fclose($Handle);
?>
在PHP中我使用解密数据验证码:
<?php
include('Crypt/RSA.php');
require('privatekey.php');
$rsa = new Crypt_RSA();
$rsa->loadKey($privatekey); // private key
$base64_string = $_GET["data"];
$base64_string = str_replace(' ', '+', $base64_string);
$ciphertext = base64_decode($base64_string);
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$plaintext = $rsa->decrypt($ciphertext);
echo $plaintext;
?>
我也做了一个PHP隐窝测试我的解密php功能的脚本。这是我encrypt.php的代码:
<?php
include('Crypt/RSA.php');
require('publickey.php');
$rsa = new Crypt_RSA();
$rsa->loadKey($publickey); // public key
$plaintext = $_GET["data"];
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$ciphertext = $rsa->encrypt($plaintext);
echo base64_encode($ciphertext);
?>
我没有问题,当加密和只使用PHP解密的文字,但如果我用的Android应用进行加密的数据,PHP给我解密错误。
感谢您的关注。
答
在你的PHP有: CRYPT_RSA_ENCRYPTION_PKCS1
但是当你在Android上创建Cipher对象省略了模式和填充
cipher = Cipher.getInstance("RSA");
你应该尝试喜欢的东西
Cipher c = Cipher.getInstance("AES/CBC/PKCS1Padding");
ref: http://developer.android.com/reference/javax/crypto/Cipher.html
什么是错误? – 323go 2014-10-03 13:35:36