java安全3

package com.ngsn.security;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
* 对称加密(加密解密的密钥一样)
* 根据自己的密码来生成一个自己的私钥
* @author John.Yao
*
*/
public class SecretKeyTest2 {

public static void main(String[] args) throws Exception{
//Cipher 此类为加密和解密提供密码功能
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
//根据AES的加密方法生成一个密钥
//SecretKey key = KeyGenerator.getInstance("AES").generateKey();
//根据密钥工厂生成密钥
//类PBEKeySpec,可以将密码视为某种原始密钥内容,由此加密机制使用其导出一个密钥
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("1234567".toCharArray()));
//此类指定随同以密码为基础的加密法 (PBE) 使用的参数集合
PBEParameterSpec param = new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8},1000);
//初始化
//Cipher.ENCRYPT_MODE 为加密模式
//key 为密钥
cipher.init(Cipher.ENCRYPT_MODE,key,param);
//对byte[] 进行加密,返回一个加密后的byte[]
byte[] result = cipher.doFinal("abcd".getBytes());
System.out.println("result----->"+new String(result));


//解密
//初始化
//Cipher.DECRYPT_MODE 为解密模式
//key 为密钥
cipher.init(Cipher.DECRYPT_MODE, key,param);
//对加密后的byte[]进行解密
byte[] b = cipher.doFinal(result);
System.out.println("b------>"+new String(b));


}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值