Java安全之对称加密与非对称加密
Java安全之对称加密与非对称加密
Java中加密分为两种方式一个是对称加密,另一个是非对称加密。对称加密是因为加密和解密的钥匙相同,而非对称加密是加密和解密的钥匙不同。
对称加密与非对称加密的区别:
对称加密称为密钥加密,速度快,但加密和解密的钥匙必须相同,只有通信双方才能知道密钥。
非对称加密称为公钥加密,算法更加复杂,速度慢,加密和解密钥匙不相同,任何人都可以知道公钥,只有一个人持有私钥可以解密。
对称加密解密:
- /*
- * 对称加密
- */
- private static void secretEncrypt() throws Exception {
- //使用Cipher的实例
- Cipher cipher =Cipher.getInstance("AES");
- //得到加密的钥匙
- SecretKey key =KeyGenerator.getInstance("AES").generateKey();
- //初始化加密操作,传递加密的钥匙
- cipher.init(Cipher.ENCRYPT_MODE,key);
- //将加密的钥匙写入secretKey.key文件中
- FileOutputStream fosKey=new FileOutputStream("secretKey.key");
- ObjectOutputStream oosSecretKey =new ObjectOutputStream(fosKey);
- oosSecretKey.writeObject(key);
- oosSecretKey.close();
- fosKey.close();
- //将加密的内容传递进去,返回加密后的二进制数据
- byte [] results =cipher.doFinal("哈哈哈哈哈".getBytes());
- //将加密后的二进制数据写入到secretContent.dat文件中
- FileOutputStream fosData=new FileOutputStream("secretContent.dat");
- fosData.write(results);
- fosData.close();
- }
- /*
- * 对称解密
- */
- private static void secretDecrypt() throws Exception{
- Cipher cipher =Cipher.getInstance("AES");
- //获取文件中的key进行解密
- FileInputStream fisKey=new FileInputStream("secretKey.key");
- ObjectInputStream oisKey =new ObjectInputStream(fisKey);
- Key key =(Key)oisKey.readObject();
- oisKey.close();
- fisKey.close();
- //初始化解密操作,传递加密的钥匙
- cipher.init(Cipher.DECRYPT_MODE,key);
- //获取文件中的二进制数据
- FileInputStream fisDat=new FileInputStream("secretContent.dat");
- //获取数据第一种方式
- byte [] src=new byte [fisDat.available()];
- int len =fisDat.read(src);
- int total =0;
- while(total<src.length){
- total +=len;
- len=fisDat.read(src,total,src.length-total);
- }
- //执行解密
- byte [] result=cipher.doFinal(src);
- fisDat.close();
- System.out.println(new String(result));
- // 读文件中的数据第二种方式
- // ByteArrayOutputStream baos =new ByteArrayOutputStream();
- // copyStream(fisDat, baos);
- // byte [] result=cipher.doFinal(baos.toByteArray());
- // fisDat.close();
- // baos.close();
- }
- // private static void copyStream(InputStream ips,OutputStream ops) throws Exception{
- // byte [] buf =new byte[1024];
- // int len=ips.read(buf);
- // while(len!=-1){
- // ops.write(buf,0,len);
- // len =ips.read(buf);
- // }
- // }
|
评论暂时关闭