美文网首页
[ 加密 ] RSA 公认目前最优秀的公钥方案之一

[ 加密 ] RSA 公认目前最优秀的公钥方案之一

作者: 一个好汉 | 来源:发表于2021-09-10 10:28 被阅读0次

    RSA 加密算法是目前最有影响力的公钥加密算法,并且被普遍认为是目前 最优秀的公钥方案之一

    RSA 是第一个能同时用于加密和数字签名 的算法

    它能够抵抗到目前为止已知的 所有密码攻击,已被 ISO 推荐为公钥数据加密标准


    RSA

    rsa-demo

    import javax.crypto.Cipher;
    import java.math.BigInteger;
    import java.nio.charset.StandardCharsets;
    import java.security.*;
    
    /**
     * RSA 公认目前最优秀的公钥方案之一
     */
    public class RsaEncrypt {
        public static void main(String[] args) throws Exception {
            // 明文:
            byte[] plain = "Hello, encrypt use RSA".getBytes(StandardCharsets.UTF_8);
            // 创建公钥/私钥对:
            Partner alice = new Partner("Alice");
            // 用Alice的公钥加密:
            byte[] pk = alice.getPublicKey();
            System.out.println(String.format("public key: %x", new BigInteger(1, pk)));
            byte[] encrypted = alice.encrypt(plain);
            System.out.println(String.format("encrypted: %x", new BigInteger(1, encrypted)));
            // 用Alice的私钥解密:
            byte[] sk = alice.getPrivateKey();
            System.out.println(String.format("private key: %x", new BigInteger(1, sk)));
            byte[] decrypted = alice.decrypt(encrypted);
            System.out.println(new String(decrypted, StandardCharsets.UTF_8));
        }
    }
    
    class Partner {
        String name;
        // 私钥:
        PrivateKey sk;
        // 公钥:
        PublicKey pk;
    
        public Partner(String name) throws GeneralSecurityException {
            this.name = name;
            // 生成公钥/私钥对:
            KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
            kpGen.initialize(1024);
            KeyPair kp = kpGen.generateKeyPair();
            this.sk = kp.getPrivate();
            this.pk = kp.getPublic();
        }
    
        // 把私钥导出为字节
        public byte[] getPrivateKey() {
            return this.sk.getEncoded();
        }
    
        // 把公钥导出为字节
        public byte[] getPublicKey() {
            return this.pk.getEncoded();
        }
    
        // 用公钥加密:
        public byte[] encrypt(byte[] message) throws GeneralSecurityException {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, this.pk);
            return cipher.doFinal(message);
        }
    
        // 用私钥解密:
        public byte[] decrypt(byte[] input) throws GeneralSecurityException {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, this.sk);
            return cipher.doFinal(input);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:[ 加密 ] RSA 公认目前最优秀的公钥方案之一

          本文链接:https://www.haomeiwen.com/subject/gtkswltx.html