JAVA AES-128-CBC加密 PHP7 OpenSSL解密失败?

C哩C哩 · · 68 次点击 · · 开始浏览    

这是一段JAVA加密的代码,现在在转化为PHP7中的OpenSSL解密中,总是返回失败,Google之后,感觉问题出现在IV偏移量上,但是不太清楚具体原因,下面贴上JAVA的加密和PHP解密的方法,希望对对称加密比较熟悉的不惜赐教。

JAVA Code:


public class SecurityUtil {
	public static byte[] encrypt(String content, String password) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(password.getBytes());
		kgen.init(128, secureRandom);

		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

		Cipher cipher = Cipher.getInstance("AES");
		byte[] byteContent = content.getBytes("utf-8");

		cipher.init(Cipher.ENCRYPT_MODE, key);
		return cipher.doFinal(byteContent);
	}

	public static byte[] decrypt(byte[] content, String password) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(password.getBytes());
		kgen.init(128, secureRandom);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, key);
		return cipher.doFinal(content);
	}

	public static String decrypt(String value, String password) {
		try {
			byte[] raw = password.getBytes();
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			IvParameterSpec iv = new IvParameterSpec(skeySpec.getEncoded());
			Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			dcipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			return new String(dcipher.doFinal(asBin(value)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

}

PHP Code: 

public static function decrypt($plainText, $key)
    {
        return openssl_decrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $key);
    }

本文来自:开源中国博客

感谢作者:C哩C哩

查看原文:JAVA AES-128-CBC加密 PHP7 OpenSSL解密失败?

68 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet