私は、メッセージを暗号化するための鍵ペアを生成するphpのWebサービスと、秘密鍵を取得してメッセージの復号化を行うjavaの1つのアプリケーションを持っています。暗号化PHP、復号化Java
私は http://phpseclib.sourceforge.net/を使用して、この二つのファイル持ってるPHP用の:
keypair.php
<?php
set_time_limit(0);
if(file_exists('private.key'))
{
echo file_get_contents('private.key');
}
else
{
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->createKey();
$res = $rsa->createKey();
$privateKey = $res['privatekey'];
$publicKey = $res['publickey'];
file_put_contents('public.key', $publicKey);
file_put_contents('private.key', $privateKey);
}
?>
encrypt.php
<?php
include('Crypt/RSA.php');
//header("Content-type: text/plain");
set_time_limit(0);
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->loadKey(file_get_contents('public.key')); // public key
$plaintext = 'Hello World!';
$ciphertext = $rsa->encrypt($plaintext);
echo base64_encode($ciphertext);
?>
とJavaで、私はこのコードを持っている:
をpackage com.example.app;
import java.io.DataInputStream;
import java.net.URL;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args)
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
try {
BASE64Decoder decoder = new BASE64Decoder();
String b64PrivateKey = getContents("http://localhost/api/keypair.php").trim();
String b64EncryptedStr = getContents("http://localhost/api/encrypt.php").trim();
System.out.println("PrivateKey (b64): " + b64PrivateKey);
System.out.println(" Encrypted (b64): " + b64EncryptedStr);
SecretKeySpec privateKey = new SecretKeySpec(decoder.decodeBuffer(b64PrivateKey) , "AES");
Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainText = decoder.decodeBuffer(b64EncryptedStr);
System.out.println(" Message: " + plainText);
}
catch(Exception e)
{
System.out.println(" Error: " + e.getMessage());
}
}
public static String getContents(String url)
{
try {
String result = "";
String line;
URL u = new URL(url);
DataInputStream theHTML = new DataInputStream(u.openStream());
while ((line = theHTML.readLine()) != null)
result = result + "\n" + line;
return result;
}
catch(Exception e){}
return "";
}
}
私の質問は次のとおりです:
- 「私はRSAキーではありません!
- このコードを改善するにはどうすればよいですか?私はbase64を使って、JavaとPHPの間のエンコーディングやコミニケーションのエラーを避けました。
- このコンセプトは正しいですか?私はそれを正しく使っていますか?
pre-base64データがデコードされたbase64データと一致していますか? –
はい、私はそれを今テストしました。また、base64でデコードされた後のPHPとJava文字列のmd5チェックサムは同じです。 –
おそらく私のSecretKeySpecが間違っていますか?私はアルゴリズムの価値を変えようとしましたが、成功しませんでした。 –