java怎么對(duì)字符串進(jìn)行加密

小億
82
2024-09-26 03:51:09

在Java中,有多種方法可以對(duì)字符串進(jìn)行加密。以下是一些常用的加密算法:

  1. AES加密:AES(Advanced Encryption Standard)是一種對(duì)稱(chēng)加密算法,使用相同的密鑰進(jìn)行加密和解密。以下是一個(gè)使用Java內(nèi)置的javax.crypto庫(kù)進(jìn)行AES加密的示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESExample {
    public static void main(String[] args) throws Exception {
        String plainText = "Hello, World!";
        String key = "ThisIsASecretKey"; // 16, 24或32個(gè)字符

        SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

        System.out.println("Encrypted Text: " + encryptedText);
    }
}

注意:在實(shí)際應(yīng)用中,不建議使用硬編碼的密鑰,而應(yīng)該將其安全地存儲(chǔ)和管理。

  1. RSA加密:RSA(Rivest-Shamir-Adleman)是一種非對(duì)稱(chēng)加密算法,使用一對(duì)密鑰進(jìn)行加密和解密。公鑰用于加密,私鑰用于解密。以下是一個(gè)使用Java內(nèi)置的javax.crypto庫(kù)進(jìn)行RSA加密的示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;

public class RSAExample {
    public static void main(String[] args) throws Exception {
        String plainText = "Hello, World!";

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

        System.out.println("Encrypted Text: " + encryptedText);

        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);

        System.out.println("Decrypted Text: " + decryptedText);
    }
}

同樣,在實(shí)際應(yīng)用中,不建議使用硬編碼的密鑰,而應(yīng)該將其安全地存儲(chǔ)和管理。

以上示例僅用于演示目的,實(shí)際應(yīng)用中可能需要根據(jù)具體需求進(jìn)行調(diào)整和優(yōu)化。在選擇加密算法時(shí),請(qǐng)確保選擇適合您需求的算法,并遵循最佳實(shí)踐來(lái)保護(hù)您的數(shù)據(jù)和系統(tǒng)安全。

0