package com.huateng.util.sm4; import javax.xml.bind.DatatypeConverter; import org.bouncycastle.util.encoders.Hex; /** * SM4/ECB/ZeroPadding */ public class SM4Utils { /** * SM4加密 * @param str 参数 * @param key 随机码 * @return */ public static String EncryptStr(String str,String key) { return DatatypeConverter.printHexBinary(new SM4_Context().EncryptByte(str.getBytes(),key.getBytes())); } /** * 解密 * @param cipherStrings 密文 * @param keyStr 随机码 * @return */ public static String DecryptStr(String cipherStrings,String keyStr) { String result = ""; SM4_Context aa=new SM4_Context(); byte[] cc="00".getBytes(); byte[] dd="00".getBytes(); byte[] cipherText = Hex.decode(cipherStrings); byte[] keyBytes = keyStr.getBytes(); try { dd= aa.DecryptStrByte(cipherText,keyBytes); result = new String(dd); } catch (Exception e) { } return result; } public static void main(String[] args) { //参数 String str = "12345";//7EFD522961B963CC3EE72A029B7F823A System.out.println("参数:" + str); //key必须是16位 String key ="efab33sddgfgf334"; String ncECBData = EncryptStr(str, key); System.out.println("加密:"+ncECBData); String encdata = "C53C319031D1ACAA41C9E7E96FA7AACF"; String plainTextEncripted = DecryptStr(encdata,key); System.out.println("解密:"+plainTextEncripted); } }