DES加密---随机获取密匙加密

1.数据加密DES--随机获取密匙加密

public static void main(String[] args) throws Exception{
//保存密钥
saveKey("my.key");
//获取密钥
SecretKey getKey = (SecretKey) getKey("my.key");
//通过密钥加密后
String result= "测试加密";
System.out.println(result+":加密前");
//对称加密后返回加密后的字节数组,
byte[] b = encrypt(getKey,result);
//解密
decrypt(b,getKey);
}
private static void getText(String aa) {
File file = new File(aa);

}



/**通过本地文件夹获取密钥*/
private static Object getKey(String path) throws Exception {
FileInputStream file = new FileInputStream(path);
ObjectInputStream inputStream = new ObjectInputStream(file);
Object object = (SecretKey) inputStream.readObject();
System.out.println(object);
return object;

}


/**创建文件夹把密钥存入本地*/
private static void saveKey(String path) throws Exception {
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
FileOutputStream file = new FileOutputStream(new File(path));
ObjectOutputStream stream = new ObjectOutputStream(file);
stream.writeObject(key);
}


/**解密*/
private static void decrypt(byte[] m, SecretKey key) throws Exception{
//对称加密使用
Cipher cipher = Cipher.getInstance("DES");
//使用加密模式
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] bs = cipher.doFinal(m);
//测试打印字节
System.out.println(new String(bs)+":解密后");
}
/**加密
* @param result */
public static byte[] encrypt(SecretKey key, String result) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {

//对称加密使用
Cipher cipher = Cipher.getInstance("DES");
//使用加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] bs = cipher.doFinal(result.getBytes());
System.out.println(new String(bs)+"加密后 ");
return bs;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值