douyingp82418
2015-04-15 14:34
浏览 42

在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

图片转代码服务由CSDN问答提供 功能建议

您好我正在编写需要加密的Android应用程序。 在Android上,我使用以下代码生成RSA密钥对;

  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创建两个二进制文件,一个是私钥,另一个是public。 我将这两个文件传输到我的开发PC进行测试,并且基本上想要使用PHP来加密一个小的消息所以扭曲以下的PHP代码;

 &lt;?php 
 \  n $ dev =“Emulator_96d68aa8156345d0”; 
 $ sz =“Duncan var Her”; 
 
echo“测试客户端生成密钥
”; 
echo $ dev。“
”; 
 
 $ cpublic_der = file_get_contents  ($ dev。“/ public”); 
 $ cprivate_der = file_get_contents($ dev。“/ private”); 
 $ cpublic_pem = der2pem($ cpublic_der); 
 
echo $ cpublic_pem。“
”; \  n 
if(openssl_public_encrypt($ sz,$ encsz,$ cpublic_pem)== true){
 echo $ sz。“
”; 
 echo“ok 
”; 
} 
 
函数der2pem($  der_data){
 $ pem = chunk_split(base64_encode($ der_data),64,“
”); 
 $ pem =“----- BEGIN CERTIFICATE ----- 
”。$ pem。“  ----- END CERTIFICATE ----- 
“; 
返回$ pem; 
} 
 
?&gt; 
   
 
 

消息 来自php PHP警告:openssl_public_encrypt():key参数不是有效的公钥

我做错了什么?

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.

    点赞 评论

相关推荐 更多相似问题