久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

Java RSA算法怎么實(shí)現(xiàn)

共計(jì) 1639 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。

Java 中可以使用 Java 內(nèi)置的加密庫 javax.crypto 來實(shí)現(xiàn) RSA 算法。

下面是一個(gè)簡(jiǎn)單的 RSA 加密和解密的示例代碼:

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

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

        // 生成公私密鑰對(duì) 
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

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

        // 使用公鑰加密數(shù)據(jù) 
        byte[] encryptedBytes = encrypt(originalText, publicKey);

        // 使用私鑰解密數(shù)據(jù) 
        String decryptedText = decrypt(encryptedBytes, privateKey);

        System.out.println("Original Text: " + originalText);
        System.out.println("Encrypted Text: " + Base64.getEncoder().encodeToString(encryptedBytes));
        System.out.println("Decrypted Text: " + decryptedText);
    }

    public static byte[] encrypt(String text, PublicKey publicKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(text.getBytes());
    }

    public static String decrypt(byte[] encryptedBytes, PrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }
}

在這個(gè)示例代碼中,首先生成一個(gè) 2048 位的 RSA 公私鑰對(duì),然后使用公鑰加密原始文本,再使用私鑰解密加密后的數(shù)據(jù)。最后輸出原始文本、加密后的文本和解密后的文本。

需要注意的是,這里使用了 Base64 編碼來將加密后的文本以字符串的形式輸出,方便觀察。在實(shí)際應(yīng)用中,可以根據(jù)需要選擇合適的方式來存儲(chǔ)和傳輸加密后的數(shù)據(jù)。

丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2023-12-13發(fā)表,共計(jì)1639字。
轉(zhuǎn)載說明:除特殊說明外本站除技術(shù)相關(guān)以外文章皆由網(wǎng)絡(luò)搜集發(fā)布,轉(zhuǎn)載請(qǐng)注明出處。
評(píng)論(沒有評(píng)論)
主站蜘蛛池模板: 共和县| 米林县| 淮滨县| 呼和浩特市| 民县| 惠东县| 永兴县| 凯里市| 无为县| 阿拉善左旗| 灵丘县| 赤水市| 东阿县| 黄骅市| 剑河县| 山东省| 平利县| 阳西县| 元氏县| 济源市| 兴国县| 石阡县| 连南| 镇江市| 黎平县| 乡城县| 阿瓦提县| 绥中县| 怀远县| 柘荣县| 鹤壁市| 科技| 安新县| 寻甸| 宜兰市| 陆川县| 会同县| 平定县| 宜州市| 伊春市| 临洮县|