Crypto前后端加密解密

问题说明
为了前后端的加解密的方式一样
AES128算法–CBC模式–填充:PKCS7Padding
CBC模式需要添加一个参数iv,秘钥偏移量
介于java 不支持PKCS7Padding,只支持PKCS5Padding
要实现在java端用PKCS7Padding填充,需要用到bouncycastle下载组件来实现
前端
Cryptojs

var key = CryptoJS.enc.Utf8.parse("0102030405060708");  //十六位十六进制数作为秘钥
        var iv  = CryptoJS.enc.Utf8.parse('0102030405060708');  //十六位十六进制数作为秘钥偏移量
        function Encrypt(word){
            srcs = CryptoJS.enc.Utf8.parse(word);
            var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv,mode:CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});
            return encrypted.ciphertext.toString().toUpperCase();
        }

        function Decrypt(word){  
            var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
            var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
            var decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv,mode:CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});
            var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8); 
            return decryptedStr.toString();
        }

        var mm = Encrypt('Test')
        console.log(mm);
        var jm = Decrypt(mm);
        console.log(jm)

后台
AES.java

package crypto;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AES {
	 // 算法名称
	 final String KEY_ALGORITHM = "AES";
	 // 加解密算法/模式/填充方式
	 final String algorithmStr = "AES/CBC/PKCS7Padding";
	 //
	 private Key key;
	 private Cipher cipher;
	 boolean isInited = false;

	 byte[] iv = "0102030405060708".getBytes();
	 public void init(byte[] keyBytes) {

	  // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
	  int base = 16;
	  if (keyBytes.length % base != 0) {
	   int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
	   byte[] temp = new byte[groups * base];
	   Arrays.fill(temp, (byte) 0);
	   System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
	   keyBytes = temp;
	  }
	  // 初始化
	  Security.addProvider(new BouncyCastleProvider());
	  // 转化成JAVA的密钥格式
	  key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
	  try {
	   // 初始化cipher
	   cipher = Cipher.getInstance(algorithmStr, "BC");
	  } catch (NoSuchAlgorithmException e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  } catch (NoSuchPaddingException e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  } catch (NoSuchProviderException e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  }
	 }
	 /**
	  * 加密方法
	  *
	  * @param content
	  *            要加密的字符串
	  * @param keyBytes
	  *            加密密钥
	  * @return
	  */
	 public byte[] encrypt(byte[] content, byte[] keyBytes) {
	  byte[] encryptedText = null;
	  init(keyBytes);
	  System.out.println("IV:" + new String(iv));
	  try {
	   cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
	   encryptedText = cipher.doFinal(content);
	  } catch (Exception e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  }
	  return encryptedText;
	 }
	 /**
	  * 解密方法
	  *
	  * @param encryptedData
	  *            要解密的字符串
	  * @param keyBytes
	  *            解密密钥
	  * @return
	  */
	 public byte[] decrypt(byte[] encryptedData, byte[] keyBytes) {
	  byte[] encryptedText = null;
	  init(keyBytes);
	  System.out.println("IV:" + new String(iv));
	  try {
	   cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
	   encryptedText = cipher.doFinal(encryptedData);
	  } catch (Exception e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  }
	  return encryptedText;
	 }
	}

Test.java

package crypto;

import org.bouncycastle.util.encoders.Hex;

public class Test {
	 public static void main(String[] args) {
	  AES aes = new AES();
	//   加解密 密钥
	  byte[] keybytes = "0102030405060708".getBytes();
	  String content = "Test";
	  // 加密字符串
	  System.out.println("加密前的:" + content);
	  System.out.println("加密密钥:" + new String(keybytes));
	  // 加密方法
	  byte[] enc = aes.encrypt(content.getBytes(), keybytes);
	  System.out.println("加密后的内容:" + new String(Hex.encode(enc)));
	  // 解密方法
	  byte[] dec = aes.decrypt(enc, keybytes);
	  System.out.println("解密后的内容:" + new String(dec));
	 }

}

运行结果对比

//前端
DC3F1A99F4D5C4B76A282C8E21D16EC9
Test

//后台
加密前的:Test
加密密钥:0102030405060708
IV:0102030405060708
加密后的内容:dc3f1a99f4d5c4b76a282c8e21d16ec9
IV:0102030405060708
解密后的内容:Test

你可能感兴趣的:(Javascript,Java)