1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JS 公開鍵 暗号化 => PHP 秘密鍵 複合

Posted at

メモ。
ここを参考にしたけど、自分の環境だとcrypto モジュールがうまく設定できなかったので、JSEncrypt を使う。

# JSEncryptを入れる
$ yarn add jsencrypt
JavaScript
import JSEncrypt from 'jsencrypt';
import axios from 'axios ';

// 公開鍵取得
const publicKey = await(async()=>{
  const res = await axios.get('/crypt/publickey');
  return res.data || "";
})();

// 暗号化
var encrypt = new JSEncrypt();
encrypt.setPublicKey(publicKey);
var encrypted = encrypt.encrypt("hogehoge@example.com");

// サーバ側で複合
const res = await axios.post('/crypt/decode', {encrypted});
console.log("res.data", res.data);
Laravel
class CryptController extends Controller
{
    public function __construct()
    {
    }

    public function publickey()
    {
        return file_get_contents(resource_path('rsa_2048_pub.pem'));
    }

    public function decode(Request $request)
    {
        $privatekey = file_get_contents(resource_path('rsa_2048_priv.pem'));
        $encrypted = base64_decode($request->encrypted);

        $decrypted = null;
        if (!openssl_private_decrypt($encrypted, $decrypted, $privatekey)){
            abort(422);
        };

        return $decrypted;
    }
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?