如何用PHP使用PhpSeclib在PHP中生成的Rsa公钥加密数据?

时间:2016-11-01 12:20:45

标签: java php android rsa phpseclib

我想在android中创建一个项目,将一些数据发送到php webservice, 我使用Aes密钥加密数据并使用从服务器接收的Rsa公钥来加密Aes密钥,但是当我将加密密钥发送到服务器时,服务器无法解密它!

在php代码中生成Pv,PB Key并发送到Android设备:

<?php 
$cipher = new Crypt_RSA();
$keypairs = $cipher->createKey();
$public_key = $keypairs['publickey'];
$private_key = $keypairs['privatekey'];
$obj = new stdClass();
$obj->query_result = "SUCCESS";
$obj->public_key = "$public_key";
$obj->private_key = "$private_key"; //send just for test 
echo (json_encode($obj));

这个公共和私人是Pem格式? :

  -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVjF8lsgjXm48cS5vj05ga1cqo KuqcyDtIcc0UBJv62jLhVo/cx/iyhcs5F+WFXjxowKZiO2rxlS6KRLY1rtuGaKF9 CVn+k8mU2Mo9QOWZINAcVTqx07fjHvRc9uOV9qqE00xl3SqmZ1NcYv9f5Y1Tynqo T0DMT+Px5Q6p9unlowIDAQAB -----END PUBLIC KEY-----

私人:

-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDVjF8lsgjXm48cS5vj05ga1cqoKuqcyDtIcc0UBJv62jLhVo/c x/iyhcs5F+WFXjxowKZiO2rxlS6KRLY1rtuGaKF9CVn+k8mU2Mo9QOWZINAcVTqx 07fjHvRc9uOV9qqE00xl3SqmZ1NcYv9f5Y1TynqoT0DMT+Px5Q6p9unlowIDAQAB AoGBAMZfr8OEr1Ia38aZNidd2F6VW7z8oRUjrG6PyMJfxcYyDDHoB5xA53Zvc2mG GWDbOaLV07pNF/tzadhoHBuiY6m1q3RQzlprHwmKGGo5L60N+DGQvNsk1DXw3HYj JYkyWqOXazrW/bEl1hJcIzYAJvzKZbT1myEAF+sc+VpQ4uKBAkEA8zOJKeOeN9ow lW7xeGhK5BrzMVfpShIepAT6TYqE+mU8gFghMXUi1ExHtwZ73H23K9fYA4+RquBh FkbMI+7afwJBAODJWBGB5r6YT9bCN1LGetqGM4fwDgfeCRWZ+k/iQ/NOaFcyoJDU F5NENCZDfsPXtw4KfqM5G0/vRGyq+QeJut0CQFggYJ+xP2/1vI0puo5rHFgz+9Px izOwBTJiK2FVxIIHlTjctop5a7mKOqJz0wY+99UHTdtcduh4jjXIScjrkHkCQQCL UsBPOaB3CZiSl5YKrBKBVyShYNyRa8Fdri5DTQ6owzRQt4Rlv89M670W6karxAwl m8OaD08qYDac0+u+DFPRAkEAwQE0Ri5bmy4whpIUpPULXL+85+vds9llaCSIBZYx kQBNFp6G59EpIOvIg1AKmTiKtine3E+LoUCW+UE34DiSlw== -----END RSA PRIVATE KEY-----

发送到Android的Json文件:

{"query_result":"SUCCESS","public_key":"-----BEGIN PUBLIC KEY-----\r\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDWDvcjZcgPZ+SiC9f27uD1j4Ws\r\naIdVk7FH3AgtDonGsV+nVtjmASrhXnrMWpXHfZ2gmtqh0s2yUwU4iJdNq4slUiF5\r\nM8M0IfFH2SqcBj0wVxozlF7FLNitKvtDSGzc0dKlgrw6ES9gBNvwulmDpk1dCn97\r\nV\/VUGFBf\/OdS55jA1wIDAQAB\r\n-----END PUBLIC KEY-----","private_key":"-----BEGIN RSA PRIVATE KEY-----\r\nMIICXgIBAAKBgQDWDvcjZcgPZ+SiC9f27uD1j4WsaIdVk7FH3AgtDonGsV+nVtjm\r\nASrhXnrMWpXHfZ2gmtqh0s2yUwU4iJdNq4slUiF5M8M0IfFH2SqcBj0wVxozlF7F\r\nLNitKvtDSGzc0dKlgrw6ES9gBNvwulmDpk1dCn97V\/VUGFBf\/OdS55jA1wIDAQAB\r\nAoGBALA\/qDtsDZqpt3W5fLukGnP2FWFMu8m5jqmVQOIga06\/MvwspPBUm8LusPtb\r\nxqF4C3Z2qne9g4JFmzHePX5FNY4mRRar2KCbNehlPr2QFljEzagych7o2374HDUY\r\np47iVqnqTbuCJumcN5K\/Ioh4qfMJGOJNIDNjYCm+KwyMsXXJAkEA9GUgX3i\/Abs+\r\nzLnXt5\/kBqbllmvUzd85V7qSFI6ANpQe3u538D4173At8zoTh9tZRIoh+tyshM9\/\r\nToWFEVFwuwJBAOA5ERG9md7DSkBvmI6kZC08t+BmmtQ6tZOUlRM5wqPEVEfanauZ\r\nCui9UDF+xOVxNHUrnGh+gTKoez1lXQ9WLJUCQQC9uef41ecKdA9bpYZmwdSmqVgg\r\nf1O0AvAkP+150eqM9E5G6L\/pnJIIcIDripFw7YMOZ2HbuwafD+qXzaWw\/RVTAkEA\r\nwDksIQFigE77wPHq356fIwkCuiY8ZeVO9Q5UHv9NlggiGNeahBnX+F8T+NqtAeZj\r\nCnAwzoRlToCR5riXZyaBYQJAetnVFJAsaBbvbLduwil\/9o7EPOZ72aNpjwC8m+Qe\r\nh7arPwDXK6jI+VbiKjR9gGpffGXC6xLHzDVgbtfUThw1Wg==\r\n-----END RSA PRIVATE KEY-----"}

在json文件中将一些\ r和\ n添加到键中,是否有问题?

这是Java加密方法:

 private static PublicKey getPublicKeyFromPemFormat(String PEMString) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException {

        BufferedReader pemReader = null;

        pemReader = new BufferedReader(new InputStreamReader(
                new ByteArrayInputStream(PEMString.getBytes("UTF-8"))));

        StringBuffer content = new StringBuffer();
        String line = null;

        while ((line = pemReader.readLine()) != null) {
            if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
                while ((line = pemReader.readLine()) != null) {
                    if (line.indexOf("-----END PUBLIC KEY") != -1) {
                        break;
                    }
                    content.append(line.trim());
                }
                break;
            }
        }
        if (line == null) {
            throw new IOException("PUBLIC KEY" + " not found");
        }
        Log.i("PUBLIC KEY: ", "PEM content = : " + content.toString());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT)));
        // return keyFactory.generatePublic(new X509EncodedKeySpec(content.toString().getBytes()));


    }


 public static String getContentWithPublicKeyFromPemFormat(String PEMString,
                                                              String content, boolean ispublic) throws NoSuchAlgorithmException,
            InvalidKeySpecException, IOException, NoSuchProviderException,
            NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {


        PublicKey publicKey = getPublicKeyFromPemFormat(PEMString);
        if (publicKey != null)
            Log.i("PUBLIC KEY: ", "FORMAT : " + publicKey.getFormat()
                    + " \ntoString : " + publicKey.toString());

        byte[] contentBytes = Base64.encode(content.getBytes(), Base64.DEFAULT);
        // byte[] contentBytes = content.getBytes();

        byte[] decoded = null;

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//BC=BouncyCastle Provider
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        decoded = cipher.doFinal(contentBytes);
        return new String(decoded, "UTF-8");

    }
什么是错的?

感谢。

0 个答案:

没有答案