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

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

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

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

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?May 08, 2025 am 12:21 AM

TheBesteptroachForendingeMailsInphPisusingThephPmailerlibraryDuetoitsReliability, featurerichness 및 reaseofuse.phpmailersupportssmtp, proversDetailErrorHandling, supportSattachments, andenhancessecurity.foroptimalu

PHP의 종속성 주입을위한 모범 사례PHP의 종속성 주입을위한 모범 사례May 08, 2025 am 12:21 AM

의존성 주입 (DI)을 사용하는 이유는 코드의 느슨한 커플 링, 테스트 가능성 및 유지 관리 가능성을 촉진하기 때문입니다. 1) 생성자를 사용하여 종속성을 주입하고, 2) 서비스 로케이터 사용을 피하고, 3) 종속성 주입 컨테이너를 사용하여 종속성을 관리하고, 4) 주입 종속성을 통한 테스트 가능성을 향상 시키십시오.

PHP 성능 튜닝 팁 및 요령PHP 성능 튜닝 팁 및 요령May 08, 2025 am 12:20 AM

phpperformancetuningiscrucialbecauseitenhancesspeedandefficies, thearevitalforwebapplications.1) cachingsdatabaseloadandimprovesResponsetimes.2) 최적화 된 databasequerieseiesecessarycolumnsingpeedsupedsupeveval.

PHP 이메일 보안 : 이메일 보내기 모범 사례PHP 이메일 보안 : 이메일 보내기 모범 사례May 08, 2025 am 12:16 AM

theBestPracticesForendingEmailsSecurelyPinphPinclude : 1) usingecureconfigurations와 whithsmtpandstarttlSencryption, 2) 검증 및 inputSpreverventInseMeStacks, 3) 암호화에 대한 암호화와 비도시를 확인합니다

성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?May 08, 2025 am 12:08 AM

tooptimizephPapplicationsperperperperperperperperperferferferferferferferferferferperferferperferperperferferfercations.1) ubsicationScachingwithApcuTeDucedAtaFetchTimes.2) 최적화 된 ABASEABASES.3)

PHP의 종속성 주입이란 무엇입니까?PHP의 종속성 주입이란 무엇입니까?May 07, 2025 pm 03:09 PM

expendencyInphpisaDesignpatternpattern thatenhances-flexibility, testability 및 maintainabilitable externaldenciestoclasses.itallowsforloosecoupling, easiertesting throughmocking 및 modulardesign, berrequirecarefultructuringtoavoid-inje

최고의 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

opCodeCachingsIntIficInlyIntImeRimproveSphpperformanceCachingCompileDCode, retingServerLoadandResponsEtimes.1) itStoresCompyledPhpCodeInMemory, BYPASSINGPARSINGCOMPILING.2) UseOpCacheSettingParametersInphP.Ini, likeMoryConsAncme AD

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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기