>  기사  >  백엔드 개발  >  플랫폼 전반에서 RSA 암호화 및 복호화를 통해 데이터 보호

플랫폼 전반에서 RSA 암호화 및 복호화를 통해 데이터 보호

DDD
DDD원래의
2024-09-29 20:07:02503검색

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 암호화는 여러 프로그래밍 환경에서 중요한 데이터를 안전하게 보호할 수 있는 안정적인 방법을 제공합니다. JavaScript, Python 및 PHP에서 RSA 암호화 및 암호 해독을 구현하면 중요한 정보를 보호하고 보안을 강화하며 플랫폼 간 호환성을 보장할 수 있습니다. API 호출 보안, 사용자 데이터 보호, 메시지 기밀성 보장 등 RSA는 강력한 암호화 솔루션을 제공합니다.

이 가이드가 도움이 되었다면 동료 개발자와 공유해 보시고 암호화 및 데이터 보안에 대한 더 많은 통찰력을 기대해 주세요!

암호화 #RSA #사이버보안 #데이터보안 #웹개발 #크로스플랫폼보안 #자바스크립트 #파이썬 #PHP

위 내용은 플랫폼 전반에서 RSA 암호화 및 복호화를 통해 데이터 보호의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.