【网络安全基础】公钥密码算法的实现二

该博客详细介绍了RSA公钥密码算法的原理,并在Eclipse环境中实现了RSA的加密和解密操作。通过将明文文件a.txt加密成b.txt,再解密到c.txt,验证了RSA算法的正确性。

公钥密码算法的实现二

1、实验要求

(1)总结RSA原理;
(2)利用现有开发工具实现RSA的求解,并对常见信息进行加解密。把明文文件a.txt中的信息加密,把密文存在b.txt中,解密信息存在c.txt中,利用函数比对明文和解密出的明文是否相同;

2、实现方法
在Eclipse中编程实现上述内容。

3、实验过程及结果
(1)总结RSA原理;
在这里插入图片描述
(2)利用现有开发工具实现RSA的求解,并对常见信息进行加解密。

public class MyRSA {
    public static final String KEY_ALGORITHM = "RSA";
    /** 貌似默认是RSA/NONE/PKCS1Padding,未验证 */
    public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
    public static final String PUBLIC_KEY = "publicKey";
    public static final String PRIVATE_KEY = "privateKey";

    /** RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024 */
    public static final int KEY_SIZE = 2048;

    public static void main(String[] args)throws Exception {
        try (BufferedReader ar = new BufferedReader(new FileReader("E:\\eclipse\\a.txt"))) {
			BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\eclipse\\b.txt"));
			BufferedWriter cw = new BufferedWriter(new FileWriter("E:\\eclipse\\c.txt"));
			Map<String, byte[]> keyMap = generateKeyBytes();
			String PLAIN_TEXT=ar.readLine();
			
	        // 加密
	        PublicKey publicKey = restorePublicKey(keyMap.get(PUBLIC_KEY));
	        byte[] encodedText = RSAEncode(publicKey, PLAIN_TEXT.getBytes());
	        String encoded="RSA encoded(Base64): " + new String(Base64.getEncoder().encode(encodedText));
	
	        // 解密
	        PrivateKey privateKey = restorePrivateKey(keyMap.get(PRIVATE_KEY));
	        String decoded = "RSA decoded: "+ RSADecode(privateKey, encodedText);
	        
	        bw.write(new String(encoded));
			bw.newLine();
			bw.close();
			cw.write(new String(decoded));
			cw.newLine();
			cw.close();
        }
    }

    /**
     * 生成密钥对。注意这里是生成密钥对KeyPair,再由密钥对获取公私钥
     * 
     * @return
     */
    public static Map<String, byte[]> generateKeyBytes() {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator
                    .getInstance(KEY_ALGORITHM);
            keyPairGenerator.initialize(KEY_SIZE);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

            Map<String, byte[]> keyMap = new HashMap<String, byte[]>();
            keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
            keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
            return keyMap;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
     * 
     * @param keyBytes
     * @return
     */
    public static PublicKey restorePublicKey(byte[] keyBytes) {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
            return publicKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 还原私钥,PKCS8EncodedKeySpec 用于构建私钥的规范
     * 
     * @param keyBytes
     * @return
     */
    public static PrivateKey restorePrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密,三步走。
     * 
     * @param key
     * @param plainText
     * @return
     */
    public static byte[] RSAEncode(PublicKey key, byte[] plainText) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(plainText);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密,三步走。
     * 
     * @param key
     * @param encodedText
     * @return
     */
    public static String RSADecode(PrivateKey key, byte[] encodedText) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(encodedText));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
 
图1:RSA加解密结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值