使用密钥加密、解密实例

xiaoxiao2021-02-27  798

package com.xiaohe.mianshi1;

import java.io.IOException; import java.security.SecureRandom;

import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec;

import Decoder.BASE64Decoder; import Decoder.BASE64Encoder;

public class DesUtil { private final static String DES = “DES”;

public static void main(String[] args) { String data = "我爱你!!"; String key = "123116爱11"; System.out.println(enctypt(data, key)); System.out.println(decrypt(enctypt(data, key), key)); } public static String enctypt(String data, String key) { byte[] bt = encrypt(data.getBytes(), key.getBytes()); String strs = new BASE64Encoder().encode(bt); return strs; } public static String decrypt(String data, String key) { System.out.println("data++++" + data); if (data == null) { return null; } BASE64Decoder decoder = new BASE64Decoder(); byte[] buf = null; try { buf = decoder.decodeBuffer(data); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(1); e.printStackTrace(); } byte[] bt = decrypt(buf, key.getBytes()); return new String(bt); } /* * 加密 */ private static byte[] encrypt(byte[] data, byte[] key) { // 生成一个可信任随机的数源 try { SecureRandom sr = new SecureRandom(); // 从原始密码数据创建DESkeySpec DESKeySpec dks = new DESKeySpec(key); // 创建一个密钥工厂,然后用它把DESKeySpec转换为SecrekKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey secretKey = keyFactory.generateSecret(dks); // Cipher对象实机完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr); return cipher.doFinal(data); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /* * 解密 */ private static byte[] decrypt(byte[] data, byte[] key) { try { // 生成一个可信任随机的数源 SecureRandom sr = new SecureRandom(); // 从原始密码数据创建DESkeySpec DESKeySpec dks = new DESKeySpec(key); // 创建一个密钥工厂,然后用它把DESKeySpec转换为SecrekKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey secretKey = keyFactory.generateSecret(dks); // Cipher对象实机完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密钥初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, secretKey, sr); return cipher.doFinal(data); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("大事不好,您的系统受到严重攻击!!!"); return null; } }

}

转载请注明原文地址: https://www.6miu.com/read-40.html

最新回复(0)