DES对称加密技术和RSA非对称加密技术


 
 
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class PrivateKey {
    
    public static void main(String[] args) throws Exception {
        String before = "kristain";
        byte[] plainText = before.getBytes("UTF-8");
        //得到一个使用AES算法的KeyGenerator的实例;
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keyGen.init(128,random);
        //通过KeyGenerator产生一个key(密钥算法已定义,为AES)
        Key key = keyGen.generateKey();
        
        //获得一个私钥加密类Cipher,定义Cipher的基本信息:ECB是加密方式,PKCS5Padding是填充方法
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        
        //使用私钥加密,把刚才生成的key当作参数,初始化使用刚才获得的私钥加密类,
        //Cipher.ENCRYPT_MODE意思是加密
        cipher.init(Cipher.ENCRYPT_MODE, key);
        
        byte[] cipherText = cipher.doFinal(plainText);
        
        cipher.init(Cipher.DECRYPT_MODE, key);
        //对刚才私钥加密的字节流进行解密,解密后返回一个字节流byte[]
        byte[] newPlainText = cipher.doFinal(cipherText);
        //String after2 = new String(newPlainText, "UTF-8");
    }
}

  (2)RSA非对称加密技术

1.A要向B发送消息,A和B都要产生一对用于加密和解密的公钥和私钥

2.A的私钥保密,A的公钥告诉B,B的私钥保密,B的公钥告诉A

3.A要给B发送信息时,A用B的公钥加密信息,因为A知道B的公钥

4.A将这个消息发送给B(已经用B的公钥加密信息)

5.B收到这个消息后,B用自己的私钥解密A的信息。其他所有收到的这个报文的人都无法解密,因为只有B才有B的私钥

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import javax.crypto.Cipher;

public class PrivateKey {
    
    public static void main(String[] args) throws Exception {
        String before = "abcdef";
        byte[] plainText = before.getBytes("UTF8");
        //产生一个RSA密钥生成器KeyPairGenerator
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        //定义一个密钥长度1024位
        keyGen.initialize(1024);
        //通过KeyPairGenerator产生密钥,这里的key是一对密钥
        KeyPair key = keyGen.generateKeyPair();
        
        //获得一个RSA的Cipher类,使用公钥加密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
        
        //用私钥解密
        byte[] cipherText = cipher.doFinal(plainText);
        cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
        byte[] newPlainText = cipher.doFinal(cipherText);
        //String after2 = new String(newPlainText,"UTF8");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值