douyingp82418 2015-04-15 14:34
浏览 48
已采纳

在php中阅读Android加密密钥

Hi I'm writing an android app that needs crypto. On Android I generate a RSA key pair using the following code;

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
SecureRandom r=SecureRandom.getInstance("SHA1PRNG");
kpg.initialize(2048,r);
KeyPair kp = kpg.generateKeyPair();
Utils.File.write(szPri,kp.getPrivate().getEncoded());
Utils.File.write(szPub,kp.getPublic().getEncoded());

My Utils.File creates two binary files one with the private key the other the public. I transfere the two files to my development PC for testing and basically want to use PHP to encrypt a small mesage so wrothe the following PHP code;

<?php

$dev="Emulator_96d68aa8156345d0";
$sz="Duncan var Her";

echo "Test Client generated key's
";
echo $dev."
";

$cpublic_der = file_get_contents($dev."/public");
$cprivate_der = file_get_contents($dev."/private");
$cpublic_pem = der2pem($cpublic_der);

echo $cpublic_pem."
";

if(openssl_public_encrypt($sz,$encsz,$cpublic_pem) == true) {
    echo $sz."
";
    echo "ok\N";
}

function der2pem($der_data) {
   $pem = chunk_split(base64_encode($der_data), 64, "
");
   $pem = "-----BEGIN CERTIFICATE-----
".$pem."-----END CERTIFICATE-----
";
   return $pem;
}

?>

Message from php PHP Warning: openssl_public_encrypt(): key parameter is not a valid public key

What am I doing wrong?

Duncan

  • 写回答

1条回答 默认 最新

  • dongmie3987067 2015-04-16 12:05
    关注

    Try to change -----BEGIN CERTIFICATE----- to -----BEGIN PUBLIC KEY----- or -----BEGIN RSA PUBLIC KEY-----. The same with END.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?