一个CryptoJS AES/ECB/NoPadding加密实现问题

梁某某 发布于 2016/09/27 11:04
阅读 595
收藏 0
public static String encrypt(String data) throws Exception {
		try {

			Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
			int blockSize = cipher.getBlockSize();

			byte[] dataBytes = data.getBytes();
			int plaintextLength = dataBytes.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength
						+ (blockSize - (plaintextLength % blockSize));
			}

			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");

			// ECB ģʽ��ʹ��IV
			// IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

			cipher.init(Cipher.ENCRYPT_MODE, keyspec);
			byte[] encrypted = cipher.doFinal(plaintext);
			return Base64.encodeToString(encrypted, Base64.DEFAULT);
			// return new sun.misc.BASE64Encoder().encode(encrypted);

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}



	上面是java代码,现在要用CryptoJS改写成JS加密,JS代码如下:

var key  = CryptoJS.enc.Utf8.parse(ENCRYPT_KEY);  //密钥 

            //var iv   = CryptoJS.enc.Latin1.parse('NoPadding');

            //iv:iv, 

var sendData= CryptoJS.enc.Utf8.parse(data);

            var encrypted = CryptoJS.AES.encrypt(sendData,key,

                    {

                        mode:CryptoJS.mode.ECB,

                        padding:CryptoJS.pad.NoPadding

                    });

            console.log("1--->"+encrypted);

            console.log(encrypted.ciphertext.toString(CryptoJS.enc.Base64));

            return encrypted.ciphertext.toString(CryptoJS.enc.Base64); //密文

相同字符串加密出来结果不一样,比如Login加密出来,java代码为Wr6w19AkZpUoYKyFE0EmSg== 然而JS代码输出为Wr6w19A= 感觉就是短了一截,求指点,谢谢
加载中
返回顶部
顶部