使用Android和PHP加密/解密

时间:2014-10-03 13:33:55

标签: php android encryption cryptography phpseclib

对不起这个问题。我已经阅读了之前的所有问题,但我的代码仍无效。 提前感谢任何能帮助我了解问题所在的人。

在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);

使用以下代码在php中生成publickey.php和privatekey.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 crypt脚本。这是我的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会在解密时给我一个错误。

感谢您的关注。

1 个答案:

答案 0 :(得分:0)

在你的PHP中有: CRYPT_RSA_ENCRYPTION_PKCS1

但是在Android上创建Cipher对象时,省略了模式和填充

cipher = Cipher.getInstance("RSA");

你应该尝试像

这样的东西
Cipher c = Cipher.getInstance("AES/CBC/PKCS1Padding");

参考: http://developer.android.com/reference/javax/crypto/Cipher.html