将PHP生成的公钥转换为Java公钥

时间:2015-01-15 15:08:17

标签: java php rsa bouncycastle phpseclib

我是Android新手,我正在开发基于客户端服务器的应用程序。我需要使用RSA算法进行加密/解密。

情景是: 1.Server必须创建一个私钥/公钥对(PHP)并将公钥发送到客户端(Android应用程序) 2.客户端应使用该公钥加密数据并发送到服务器 3.现在服务器必须使用私钥解密。

在PHP中,我使用' PhpSecLib '来创建密钥对。

这是编码:

Server.php:

<?PHP
include 'Crypt/RSA.php';
$rsa = new Crypt_RSA();
extract($rsa->createKey(1024));
echo $publickey;
?>

生成的公钥:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLz4yAo1FTOLc6nijBCTv5iVnW F6MxCeM5 + RXY + 29AXcpMWhlM9oES3ESIfWw6OzrrENDyqwY + kVzCj2bWYnEAyJXs WOpvqT2XSCPplwZOnQQGm + DnAYJXEeOfgU5DI63fwdiGv4M2ph1VMMe6684sBZu1 HhJHuhsX2eibBR0 / lQIDAQAB

现在在Java中,我成功收到了这个公钥并存储在一个字符串中。

编码:

protected String doInBackground(Void... params) 
{
    try
    {
    URL url=new URL("http://10.0.2.2/Samples/Server.php");
    URLConnection con=url.openConnection();
    con.setDoOutput(true);
    BufferedReader ip=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String tmp,res="";

    while((tmp=ip.readLine())!=null)
    {
        res+=tmp;

    }

    return res; //res contains the public key


    }
    catch(Exception e)
    {
        return new String("Exception : "+e.getMessage());
    }

}

我在java中使用 Bouncy castle provider(bcprov-jdk15on-151)

现在我不知道如何将此字符串转换为RSA公钥。

请建议一些代码片段?如果代码需要改进和更正,请更正。

...谢谢

1 个答案:

答案 0 :(得分:1)

假设您正确下载了密钥,可以使用base 64 encoding中的密钥生成java.security.PublicKey,其代码如下:

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

public class ParseRsaPublicKey {

    public static void main(String[] args) throws Exception {
        String yourKeyB64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLz4yAo1FTOLc6nijBCTv5iVnW\n"+
                "F6MxCeM5+RxY+29AXcpMWhlM9oES3ESIfWw6OzrrENDyqwY+kVzCj2bWYnEAyJXs\n"+
                "WOpvqT2XSCPplwZOnQQGm+DnAYJXEeOfgU5DI63fwdiGv4M2ph1VMMe6684sBZu1\n"+
                "HhJHuhsX2eibBR0/lQIDAQAB";
        // create the key factory
        KeyFactory kFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
        // decode base64 of your key
        byte yourKey[] =  Base64.decode(yourKeyB64);
        // generate the public key
        X509EncodedKeySpec spec =  new X509EncodedKeySpec(yourKey);
        PublicKey publicKey = (PublicKey) kFactory.generatePublic(spec);
        // now you can for example cipher some data with your key
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipherData = cipher.doFinal("someData".getBytes());
        System.out.println(new String(cipherData));
    }

}

希望这有帮助,