项目中要用到加密与解密,从网上找了一个修改了一下
- package com.taiji.fzb.util;
-
- import javax.crypto.*;
- import javax.crypto.spec.DESKeySpec;
-
- import java.security.NoSuchAlgorithmException;
- import java.security.InvalidKeyException;
- import java.security.SecureRandom;
- import java.security.spec.InvalidKeySpecException;
-
-
-
-
-
-
-
- public class EncryptDecryptData {
-
- public static void main(String[] args) throws NoSuchAlgorithmException,
- InvalidKeyException, NoSuchPaddingException,
- InvalidKeySpecException, IllegalBlockSizeException,
- BadPaddingException {
-
-
- SecureRandom sr = new SecureRandom();
-
- KeyGenerator kg = KeyGenerator.getInstance("DES");
- kg.init(sr);
-
- SecretKey key = kg.generateKey();
-
-
- byte rawKeyData[] = "sucre".getBytes();
- System.out.println("密匙===>" + rawKeyData);
-
- String str = "hi.baidu.com/beijingalana";
-
- byte[] encryptedData = encrypt(rawKeyData, str);
-
- decrypt(rawKeyData, encryptedData);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static byte[] encrypt(byte rawKeyData[], String str)
- throws InvalidKeyException, NoSuchAlgorithmException,
- IllegalBlockSizeException, BadPaddingException,
- NoSuchPaddingException, InvalidKeySpecException {
-
- SecureRandom sr = new SecureRandom();
-
- DESKeySpec dks = new DESKeySpec(rawKeyData);
-
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey key = keyFactory.generateSecret(dks);
-
- Cipher cipher = Cipher.getInstance("DES");
-
- cipher.init(Cipher.ENCRYPT_MODE, key, sr);
-
- byte data[] = str.getBytes();
-
- byte[] encryptedData = cipher.doFinal(data);
-
- System.out.println("加密后===>" + encryptedData);
- return encryptedData;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String decrypt(byte rawKeyData[], byte[] encryptedData)
- throws IllegalBlockSizeException, BadPaddingException,
- InvalidKeyException, NoSuchAlgorithmException,
- NoSuchPaddingException, InvalidKeySpecException {
-
- SecureRandom sr = new SecureRandom();
-
- DESKeySpec dks = new DESKeySpec(rawKeyData);
-
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey key = keyFactory.generateSecret(dks);
-
- Cipher cipher = Cipher.getInstance("DES");
-
- cipher.init(Cipher.DECRYPT_MODE, key, sr);
-
- byte decryptedData[] = cipher.doFinal(encryptedData);
- System.out.println("解密后===>" + new String(decryptedData));
- return new String(decryptedData);
- }
-
- }
在使用的时候密码数据可以调用固定的方法,也可以自己填写,我是自己写的。
本文转自sucre03 51CTO博客,原文链接:http://blog.51cto.com/sucre/531757,如需转载请自行联系原作者