Thuật toán RSA trong Java

Học sinh học lập trình

Thuật toán RSA (Rivest-Shamir-Adleman) là một thuật toán mã hóa khóa công khai phổ biến dùng trong bảo mật thông tin. Trong Java, bạn có thể sử dụng thư viện có sẵn như java.securityjavax.crypto để triển khai RSA một cách dễ dàng.

Dưới đây là một ví dụ đầy đủ và đơn giản về mã hóa và giải mã bằng thuật toán RSA trong Java:

🛠 1. Tạo cặp khóa RSA (public/private)

import java.security.*;

public class RSAGenerateKeys {
    public static void main(String[] args) throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048); // Độ dài khóa: 2048 bit

        KeyPair pair = keyGen.generateKeyPair();
        PublicKey publicKey = pair.getPublic();
        PrivateKey privateKey = pair.getPrivate();

        System.out.println("Khóa công khai:\n" + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        System.out.println("\nKhóa bí mật:\n" + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
    }
}

🔐 2. Mã hóa bằng khóa công khai

import java.security.*;
import javax.crypto.Cipher;
import java.util.Base64;

public class RSAEncrypt {
    public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher encryptCipher = Cipher.getInstance("RSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] encryptedBytes = encryptCipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
}

🔓 3. Giải mã bằng khóa riêng

import java.security.*;
import javax.crypto.Cipher;
import java.util.Base64;

public class RSADecrypt {
    public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher decryptCipher = Cipher.getInstance("RSA");
        decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }
}

🧪 4. Chạy chương trình demo

import java.security.*;

public class RSADemo {
    public static void main(String[] args) throws Exception {
        // Tạo cặp khóa
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair pair = keyGen.generateKeyPair();
        PublicKey pubKey = pair.getPublic();
        PrivateKey privKey = pair.getPrivate();

        // Văn bản gốc
        String originalText = "Xin chào, đây là RSA!";

        // Mã hóa
        String encrypted = RSAEncrypt.encrypt(originalText, pubKey);
        System.out.println("Mã hóa: " + encrypted);

        // Giải mã
        String decrypted = RSADecrypt.decrypt(encrypted, privKey);
        System.out.println("Giải mã: " + decrypted);
    }
}

Lưu ý:

  • Không nên mã hóa dữ liệu lớn trực tiếp bằng RSA. RSA chỉ nên dùng để mã hóa khóa đối xứng, sau đó dùng thuật toán như AES để mã hóa dữ liệu.
  • Dữ liệu được mã hóa phải nhỏ hơn chiều dài khóa – padding. Với khóa 2048-bit, bạn chỉ mã hóa được khoảng 245 byte.