简体   繁体   English

用RSA加密并以base64编码的php文本在android中解密后不保留一些

[英]php text encrypted with RSA in and base64 encoded doesnt remain some after decryption in android

i am using android to create a key pair, i use http post to send the public key to a wamp server mysql data base using a php script. 我正在使用android创建密钥对,我使用http post使用php脚本将公钥发送到wamp服务器mysql数据库。

after successfully receiving the key, the php scripts encrypts a string using the key and encoding it with base43, the sripts echos a json object to android.....where i decode using base64 and then use the private key to decrypt the text and then base64encode it again to view it. 成功接收密钥后,PHP脚本使用密钥对字符串进行加密,并使用base43对其进行编码,代码片段将json对象回显到android .....在这里,我使用base64进行解码,然后使用私钥对文本进行解密并然后再次对其进行base64编码以进行查看。

php 的PHP

$rawKey = $_POST['rawKey'];
$publicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split($rawKey) .  
"-----END RSA PUBLIC KEY-----";
$rsa = new Crypt_RSA();
$rsa->loadKey($publicKey); // public key
$AESKeyString = "some text";
$AESKeyString = $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($AESKeyString);
$ciphertext = base64_encode($ciphertext);
$response = array('' => $ciphertext);
echo json_encode($response);

java 爪哇

public String Decrypt(String encryptedKey) {
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} try {
    cipher.init(Cipher.DECRYPT_MODE, privKey);
} catch (InvalidKeyException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
byte[] cipherData = null;
try {
    cipherData = cipher.doFinal(Base64.decode(encryptedKey, Base64.NO_WRAP));
} catch (IllegalBlockSizeException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (BadPaddingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    String cipherString = Base64.encodeToString(cipherData, Base64.NO_WRAP);
    Log.d("SecCom", cipherString);
    return cipherString;
}

the problem WAS that although there were no errors in decryption the text was always garbage....however this garbage was unique and same for a give plaintext....that is to say "hello world" in java would always translate to "n;lk@;la" and only changing the plain text would change the decrypted garbage. 问题是,尽管解密没有错误,但文本始终是垃圾。...但是,此垃圾是唯一的,并且对于给定纯文本也是相同的。...也就是说,java中的“ hello world”将始终转换为“ n; lk @; la”,而仅更改纯文本将更改解密的垃圾。

i looked at numerous examples on stackoverflow and this seemed to work for them and purely out of some gut feeling i added a base64 decode to the php string before encrypting it 我看了许多关于stackoverflow的示例,这似乎对他们有用,并且纯粹出于某种直觉,我在加密之前在PHP字符串中添加了base64解码

$AESKeyString = base64_decode("some text");

and viola this solved the problem except for the fact that now i get origional string in java except that all the spaces are removed..... and the last character is replaced by g== 和中提琴这解决了问题,除了现在我在Java中得到原始字符串之外,除了所有空格都被删除了.....,最后一个字符替换为g ==

that is "some text" appears as "sometexg==" 那是“一些文本”显示为“ sometexg ==“

i have tried numerous texts but this is constant through all no spaces and last character replaced by g== 我已经尝试了许多文本,但是在所有空格和最后一个字符都被g ==取代的情况下这是恒定的

in my final php script i will be generating random bytes for aes, encrypting them and then encoding them to send to java. 在我最终的php脚本中,我将为es生成随机字节,将其加密,然后编码以发送给java。 please keep this in mind in the solution that you provide me..... 请在您提供给我的解决方案中牢记这一点.....

also why did adding base64.decode in php was necessary for me yet for others it worked just out of the box 也为什么为什么在PHP中添加base64.decode对我来说是必要的,但对于其他人来说,它开箱即用

thanks 谢谢

as i mentioned in my comments.... my problem was not understanding the String and encoding part and how it tranlates to java..... 正如我在评论中提到的...。我的问题是不了解字符串和编码部分以及它如何转换为java .....

well i gave it a go, did a bit of reading and rewrote the php side and it worked in the first attempt..... 好吧,我试了一下,做了一些阅读,重新编写了php端,并且在第一次尝试中就起作用了.....

.... here is a full working php code....the java code does not need to be changed....i have also commented it ....这是一个完整的工作php代码.... java代码不需要更改....我也对此进行了评论

php //get the posted public key $pumpumString = $_POST['pumpum']; php //获取发布的公钥$ pumpumString = $ _POST ['pumpum'];

    //format public key in CRYPT format
    $publicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split($pumpumString) . 
    "-----END RSA PUBLIC KEY-----";

    //initialise Algorithm
    $rsa = new Crypt_RSA();
    $rsa->loadKey($publicKey); // public key
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);

    //generate new AES Session Key
    $AESKey = rand_sha1(32); //a custom created function

    $AESKeyDecoded = base64_decode($AESKey);

    //encrypt AES Session Key
    $ciphertext = $rsa->encrypt($AESKeyDecoded);

    //base 64 encode it for transfer over internet
    $ciphertextEncoded = base64_encode($ciphertext);

    //prepare array for sending to client
    $response = array('plum' => $ciphertextEncoded);

    //write the encoded and decoded AES Session Key to file for comparison
    $file = fopen('key.txt', 'w');
    fwrite($file, "\n". $AESKey);

    //echo JSON
    echo json_encode($response);

one of the things that puzzled me earlier was why i needed to base64 decode my plaintext before encryption....well what i have been able to figure out is that, php probably uses ASCII to store strings. 早些令我困惑的一件事就是为什么我需要在加密之前需要对base64进行纯文本解码。...嗯,我能够弄清楚的是,php可能使用ASCII来存储字符串。 since in java i am using a base64_encode to get the decrypted string from the decrypted byte array.....i need to first decode my ascii plaintext string to regenerate it in java......(i might have worded that a bit non-coherently...please feel free to reword it.) 因为在Java中,我正在使用base64_encode从解密的字节数组中获取解密的字符串.....我需要先对我的ascii纯文本字符串进行解码才能在java中重新生成它......(我可能说过a有点不连贯...请随时改写它。)

if u feel that i have come to the wrong conclusion or something can be bettered please let me know, i am marking this as solved.... 如果您认为我得出了错误的结论或可以改善的地方,请告诉我,我将其标记为已解决。

also i had asked for a way to generate a random aes key.....below is the function i used to do it.....courtesy https://stackoverflow.com/a/637322/2208279 我也问过一种生成随机aes密钥的方法.....下面是我用来做的功能.....礼貌https://stackoverflow.com/a/637322/2208279

php 的PHP

function rand_sha1($length) {
    $max = ceil($length / 40);
    $random = '';
    for ($i = 0; $i < $max; $i ++) {
        $random .= sha1(microtime(true).mt_rand(10000,90000));
    }
return substr($random, 0, $length);
}

i am using a aes256 so i have used 32 as the argument to this function....modify it to 16 for 128 我正在使用aes256,所以我已经使用32作为此函数的参数....将其修改为16表示128

thanks....hope this helps someone. 谢谢....希望这可以帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RSA使用Android中的base64编码公钥进行加密 - RSA encrypt with base64 encoded public key in Android 为什么在加密的base64编码字符串中添加字符不会破坏解密? - Why does adding a character to an encrypted base64 encoded string NOT break the decryption? 为什么在Windows和Linux上加密和以base64编码的文本看起来有所不同 - Why encrypted and base64 encoded text appears different on Windows and Linux 通过URL后不保留以Base64编码的加密字符串吗? - Encrypted String encoded in Base64 not preserved after going through URL? 检查 base64 文本是否是有效的 RSA 公钥 (4096) - Check if a base64 text is a valid RSA public key (4096) Java中图像的Base64编码字符串在php中无效 - Base64 encoded string for image in java is not valid in php base64 编码字符串:可以在 PHP 但不是 Java 中解码? - base64 encoded string: can be decoded in PHP but not Java? 使用 RSA 的加密套接字连接 java(IllegalArgumentException:非法 base64 字符 10) - Encrypted socket connection java using RSA (IllegalArgumentException: Illegal base64 character 10) Android:如何检查字符串是否为 Base64 编码? - Android: How to check if string is Base64 encoded? Android下载Base64编码的数据,对其进行解码并将其保存到文件 - Android Download Base64 Encoded data, decode it and save it to file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM