您的位置:首页 > 其它

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

2016-03-30 20:56 543 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: