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

来源:互联网 发布:qq for ubuntu 14.04 编辑:程序博客网 时间:2024/06/09 14:18

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