DES对 json 、http参数加密解密算法
网上众多大神们的众多方式实现加解密操作及保障数据安全性。今天无意中发现一篇以 DES加密解密算法。摘抄如下
工具类:
import java.security.SecureRandom; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * 类 名 称:AESEncryptTools * 类 描 述:DES加密解密算法 */ public final class DESEncryptTools { //加密算是是des private static final String ALGORITHM = "DES"; //转换格式 private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding"; //利用8个字节64位的key给src加密 public static byte[] encrypt(byte[] src, byte[] key) { try { //加密 Cipher cipher = Cipher.getInstance(TRANSFORMATION); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM); KeySpec keySpec = new DESKeySpec(key); SecretKey secretKey = secretKeyFactory.generateSecret(keySpec); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom()); byte[] enMsgBytes = cipher.doFinal(src); return enMsgBytes; } catch (Exception e) { e.printStackTrace(); } return null; } //利用8个字节64位的key给src解密 public static byte[] decrypt(byte[] encryptBytes,byte[] key){ try { //解密 //Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); Cipher deCipher = Cipher.getInstance(TRANSFORMATION); SecretKeyFactory deDecretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM); KeySpec deKeySpec = new DESKeySpec(key); SecretKey deSecretKey = deDecretKeyFactory.generateSecret(deKeySpec); deCipher.init(Cipher.DECRYPT_MODE, deSecretKey, new SecureRandom()); byte[] deMsgBytes = deCipher.doFinal(encryptBytes); return deMsgBytes; } catch (Exception e) { e.printStackTrace(); } return null; } }
测试类:
import com.gzewell.ucomweb.util.DESEncryptTools; public class DesMainTest { private static String key = "52linnuo"; public static void main(String[] args) throws Exception{ String msg = "hello world. hello ucom, 林诺欧巴"; System.out.println("加密前:"+msg); byte[] encryptBytes = DESEncryptTools.encrypt(msg.getBytes(),key.getBytes()); System.out.println("加密后:"+new String(encryptBytes)); byte[] deMsgBytes = DESEncryptTools.decrypt(encryptBytes,key.getBytes()); System.out.println("解密后:"+new String(deMsgBytes)); } }
运行如下:
加解密用同一串 key 则加以保障数据安全,撸码再也不用担心被抓包了~
ps: key不能为 8 为以下纯数字或纯字母