java 加解密小 demo

今天在拉钩教育专栏《计算机网络通关29讲》上看的

// --- 私钥加密,公钥解密 ---
        KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
        KeyPair pair = rsa.generateKeyPair();
        byte[] encodedKey = pair.getPrivate().getEncoded();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
        PrivateKey pkey = keyFactory.generatePrivate(keySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, pkey);
        String str = "hello";
        byte[] encodedBytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));

        byte[] publicKey = pair.getPublic().getEncoded();
        X509EncodedKeySpec keySpec1 = new X509EncodedKeySpec(publicKey);
        PublicKey pubKey = keyFactory.generatePublic(keySpec1);
        Cipher cipher1 = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher1.init(Cipher.DECRYPT_MODE, pubKey);
        byte[] hello = cipher1.doFinal(encodedBytes);
        System.out.println(new String(hello));
// --- 对称加解密 ---
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] ivBytes = "1111111111111111".getBytes();
        cipher2.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivBytes));
        byte[] out2 = cipher2.doFinal("woqiao!".getBytes());

        Cipher cipher21 = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher21.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));
        byte[] woqiao = cipher21.doFinal(out2);
        System.out.println(new String(woqiao));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值