検索
ホームページバックエンド開発PHPチュートリアルRSA 暗号化と復号化によるプラットフォーム間でのデータの保護

Securing Data with RSA Encryption and Decryption Across Platforms

Introduction to RSA Encryption

In today's digital landscape, securing sensitive data is crucial for individuals and organizations alike. RSA (Rivest-Shamir-Adleman) encryption stands out as a robust solution for protecting data. It is an asymmetric encryption algorithm, which means that it uses a pair of keys: a public key for encryption and a private key for decryption. One of the main benefits of RSA encryption is that the private key never needs to be shared, which minimizes the risk of it being compromised.

This article explores how to use RSA encryption across three popular programming languages—JavaScript, Python, and PHP—making it easier to secure data in cross-platform applications.

Cross-Platform Encryption and Decryption: The Scenario

Imagine you're building a web application where sensitive information (like authentication data or personal details) must be securely transmitted between the client (front end) and the server (back end). For instance, you might encrypt a message on the client side in JavaScript and then decrypt it on the server using either Python or PHP.

RSA is well-suited for this scenario because it provides the flexibility of encryption in one language and decryption in another, ensuring cross-platform compatibility.

RSA Implementation: JavaScript, Python, and PHP

JavaScript (Next.js with JSEncrypt)
Encryption:

import JSEncrypt from 'jsencrypt';

// Function to encrypt a message using a public key
const encryptWithPublicKey = (message) => {
  const encryptor = new JSEncrypt();
  const publicKey = process.env.NEXT_PUBLIC_PUBLIC_KEY.replace(/\\n/g, "\n");
  encryptor.setPublicKey(publicKey);
  const encryptedMessage = encryptor.encrypt(message);
  return encryptedMessage;
};

Decryption:

import JSEncrypt from 'jsencrypt';

// Function to decrypt a message using a private key
const decryptWithPrivateKey = (encryptedMessage) => {
  const decryptor = new JSEncrypt();
  const privateKey = process.env.PRIVATE_KEY.replace(/\\n/g, "\n");
  decryptor.setPrivateKey(privateKey);
  const decryptedMessage = decryptor.decrypt(encryptedMessage);
  return decryptedMessage;
};

Explanation:

Public Key Encryption: The JSEncrypt library encrypts the message using the public key. This ensures that only the corresponding private key can decrypt it.
Private Key Decryption: The message is decrypted with the private key, which is securely stored in an environment variable.
Security Consideration: By using RSA, we ensure that the data sent from the client is encrypted and secure.

Python (using rsa library)
Encryption:

import rsa
import base64

def encrypt_with_public_key(message: str, public_key_str: str) -> str:
    public_key = rsa.PublicKey.load_pkcs1_openssl_pem(public_key_str.encode())
    encrypted_message = rsa.encrypt(message.encode(), public_key)
    return base64.b64encode(encrypted_message).decode()

Decryption:

import rsa
import base64

def decrypt_with_private_key(encrypted_message: str, private_key_str: str) -> str:
    private_key = rsa.PrivateKey.load_pkcs1(private_key_str.encode())
    encrypted_bytes = base64.b64decode(encrypted_message.encode())
    decrypted_message = rsa.decrypt(encrypted_bytes, private_key)
    return decrypted_message.decode()

Explanation:

Public Key Encryption: The message is encrypted using a public key, ensuring that only the intended private key holder can decrypt it.
Base64 Encoding: After encryption, the message is Base64 encoded to ensure compatibility with text transmission.
Private Key Decryption: The private key is used to decrypt the Base64-encoded encrypted message, ensuring confidentiality.

PHP (using OpenSSL)
Encryption:

function encrypt_with_public_key($message) {
    $publicKey = getenv('PUBLIC_KEY');
    openssl_public_encrypt($message, $encrypted, $publicKey);
    return base64_encode($encrypted);
}

Decryption:

function decrypt_with_private_key($encryptedMessage) {
    $privateKey = getenv('PRIVATE_KEY');
    $encryptedData = base64_decode($encryptedMessage);
    openssl_private_decrypt($encryptedData, $decrypted, $privateKey);
    return $decrypted;
}

Explanation:

Public Key Encryption: The openssl_public_encrypt function encrypts the message using the public key, ensuring that only the private key can decrypt it.
Private Key Decryption: The openssl_private_decrypt function decrypts the message using the private key, ensuring that sensitive information remains secure.
Environment Variables: Both the public and private keys are securely stored in environment variables, enhancing security.

Best Practices for Encryption

Use Environment Variables: Always store your keys in environment variables instead of hard-coding them into your application. This reduces the risk of exposing sensitive information.
Encrypt Sensitive Data: Encrypt personal and sensitive data such as passwords, financial details, or personally identifiable information (PII) to prevent unauthorized access.
Use HTTPS: Ensure your application communicates over HTTPS to safeguard data in transit.
Secure Key Management: Regularly rotate encryption keys and ensure they are stored securely.

Why Choose RSA Encryption?

Enhanced Data Security: RSA encryption ensures that sensitive data is kept secure during transmission, preventing unauthorized access.
Asymmetric Encryption: RSA uses a public key for encryption and a private key for decryption, which ensures the private key never needs to be shared.
Cross-Platform Compatibility: RSA works seamlessly across different platforms and programming languages, making it ideal for web applications where different technologies are used on the client and server sides.

結論

RSA 暗号化は、複数のプログラミング環境にわたって機密データを保護する信頼性の高い方法を提供します。 RSA 暗号化と復号化を JavaScript、Python、PHP に実装することで、機密情報を保護し、セキュリティを強化し、クロスプラットフォーム互換性を確保できます。 API 呼び出しの保護、ユーザー データの保護、メッセージの機密性の確保など、RSA は堅牢な暗号化ソリューションを提供します。

このガイドが役立つと思われた場合は、他の開発者とこのガイドを共有することを検討してください。暗号化とデータ セキュリティについてのさらなる洞察を今後もお楽しみください!

暗号化 #RSA #サイバーセキュリティ #データセキュリティ #Web開発 #クロスプラットフォームセキュリティ #JavaScript #Python #PHP

以上がRSA 暗号化と復号化によるプラットフォーム間でのデータの保護の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
PHPを使用して電子メールを送信する最良の方法は何ですか?PHPを使用して電子メールを送信する最良の方法は何ですか?May 08, 2025 am 12:21 AM

BestappRoachforseminginphpisusingthephpmailerlibrarydueToitsReliability、featurrichness、andeaseofuse.phpmailerSupportssmtpは、detairederorhandlingを提供します

PHPでの依存関係注射のベストプラクティスPHPでの依存関係注射のベストプラクティスMay 08, 2025 am 12:21 AM

依存関係注射(DI)を使用する理由は、コードのゆるい結合、テスト可能性、および保守性を促進するためです。 1)コンストラクターを使用して依存関係を注入します。2)サービスロケーターの使用を避け、3)依存関係噴射コンテナを使用して依存関係を管理する、4)依存関係を注入することでテスト可能性を向上させる、5)注入依存性を回避、6)パフォーマンスに対するDIの影響を考慮します。

PHPパフォーマンスのチューニングのヒントとコツPHPパフォーマンスのチューニングのヒントとコツMay 08, 2025 am 12:20 AM

phpperformancetuningisucial cuseenhancess andandandadsand。

PHP電子メールセキュリティ:電子メールを送信するためのベストプラクティスPHP電子メールセキュリティ:電子メールを送信するためのベストプラクティスMay 08, 2025 am 12:16 AM

bestpracticesforsendingemails securlyinphpinclude:1)sutureconsmttarttlsencryptionとの使用の使用、2)検証およびサンシジン化のinputStopReventinjectuctacks、3)adinitivedinitivedInemailsopenslsl、4)adlinglinglingemailoaに

パフォーマンスのためにPHPアプリケーションをどのように最適化しますか?パフォーマンスのためにPHPアプリケーションをどのように最適化しますか?May 08, 2025 am 12:08 AM

tooptimizephpapplicationsforporformance、usecaching、databaseoptimization、opcodecaching、andserverconfiguration.1)cachingwithedatedatedatafethtimes.2)最適化バイズビーインデキシング、readedandandandwriteoperations.3)

PHPの依存噴射とは何ですか?PHPの依存噴射とは何ですか?May 07, 2025 pm 03:09 PM

依存関係の依存性、テスト可能性、および維持可能性の依存性の依存性の依存性、および維持可能性は、エクステルンド依存性を維持する可能性があります

最高のPHPパフォーマンス最適化手法最高のPHPパフォーマンス最適化手法May 07, 2025 pm 03:05 PM

PHPパフォーマンスの最適化は、次の手順を通じて実現できます。1)スクリプトの上部にrequire_onceまたはinclude_onceを使用して、ファイルの負荷数を減らすことができます。 2)プリプロセシングステートメントとバッチ処理を使用して、データベースクエリの数を減らします。 3)OpCodeキャッシュのOpCacheを構成します。 4)PHP-FPM最適化プロセス管理を有効にして構成します。 5)CDNを使用して静的リソースを配布します。 6)コードパフォーマンス分析には、XdebugまたはBlackfireを使用します。 7)配列などの効率的なデータ構造を選択します。 8)最適化実行のためのモジュラーコードを記述します。

PHPパフォーマンスの最適化:OpCodeキャッシングの使用PHPパフォーマンスの最適化:OpCodeキャッシングの使用May 07, 2025 pm 02:49 PM

opcodeCachingsificlyprovesppherformanceBycachingCompiledCode、reducingServerloadandResponsetimes.1)itStoresPhpCodeInMemory、バイパス補助補強団体

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター