解决Linux下AES解密失败

前段时间,用了个AES加密解密的方法,详见上篇博客AES加密解密。加解密方法在window上测试的时候没有出现任何问题,将加密过程放在安卓上,解密发布到Linux服务器的时候,安卓将加密的结果传到Linux上解密的时候却总是失败,让用户不能成功登录,经过检查,测试后,发现AES在Linux上解密失败,出现错误:

javax.crypto.BadPaddingException: Given final block not properly padded

现在来回顾下自己的解决思路:

加密过程是在安卓上,解密是在Linu上,会不会是因为环境的不同,在加密过程中产生的二进制和在解密过程中产生的二进制不一样呢?可是在经过联调后,比对二进制,发现没有问题。那问题是在哪里呢?

继续联调, 仔细比对加密和解密过程中每一步产生的结果,发现了问题:

Linux解密端:

发现这里的cipher下的 firstService是有值的。

安卓加密端:

发现这里的cipher下的 firstService是没有值的。

百度后发现:

加密解密方法的唯一差别是Cipher对象的模式不一样,这就排除了程序写错的可能性。因为错误信息是在宜昌中出现的,其大概意思是:提供的字块不符合填补的。什么意思呢?原来在用加密的时候,最后一位长度不足,它会自动补足,那么在我们进行字节数组到字串的转化过程中,可以把它填补的不可见字符改变了,所以系统抛出异常。

问题找到,怎么解决呢?方式如下:

package ICT.base.rest.services.app;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESDecodeUtils {
	public static void main(String[] args) {

		String content = "g25";
		String pwd = "8182838485";
		String addPwd = "123456";

		// 加密
		System.out.println("加密前content:" + content);
		byte[] enAccount = encrypt(content, addPwd);
		byte[] enPwd = encrypt(pwd, addPwd);
		String encryptResultStr = parseByte2HexStr(enAccount);
		String parseByte2HexStr2 = parseByte2HexStr(enPwd);
		System.out.println("加密后content:" + encryptResultStr);

		// 解密 ——账号/身份证号
		byte[] accountFrom = AESDecodeUtils.parseHexStr2Byte(encryptResultStr);
		byte[] deAccount = AESDecodeUtils.decrypt(accountFrom, addPwd);
		String userAccount = new String(deAccount);
		System.out.println("解密后content:" + userAccount);
		// 解密——密码
		byte[] pwdFrom = AESDecodeUtils.parseHexStr2Byte(parseByte2HexStr2);
		byte[] deUserPwd = AESDecodeUtils.decrypt(pwdFrom, addPwd);
		String userPwd = new String(deUserPwd);
		// System.out.println(userPwd);
	}

	/**
	 * AES加密
	 *
	 * @param content
	 *            要加密的内容
	 * @param password
	 *            加密使用的密钥
	 * @return 加密后的字节数组
	 */
	public static byte[] encrypt(String content, String password) {
		SecureRandom random = null;
		try {
			<span style="color:#ff0000;">random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes());</span>
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}

		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			// kgen.init(128, new SecureRandom(password.getBytes()));
			<span style="color:#ff0000;">kgen.init(128, random);</span>
			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);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将二进制转换成16进制 加密
	 *
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 解密
	 *
	 * @param content
	 *            待解密内容
	 * @param password
	 *            解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String password) {
		SecureRandom random = null;
		try {
			<span style="color:#ff0000;">random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes());</span>
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			// kgen.init(128, new SecureRandom(password.getBytes()));
			<span style="color:#ff0000;">kgen.init(128, random);</span>
			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);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将16进制转换为二进制
	 *
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
					16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}
}

运行结果:

将加密放到安卓端,解密放大Linux上后,如下:

此时cipher下的 firstService不再是Null,都有了值

安卓加密端:

Linux解密端:

总结:

AES是对称加密,解密端改变解密过程,同样,加密端的加密过程也会改变,不管怎么着,调程序还是得要有耐心,用一个东西,其简单基本的原理还是要知道的。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-23 06:19:22

解决Linux下AES解密失败的相关文章

解决Linux下Svn检出Windows SVN服务器上项目SSL handshake failed: SSL error: Key usage violation in certificate has been detected.

在Linux上检出windows SVN服务器上项目时出现了SSL handshake failed: SSL error: Key usage violation in certificate has been detected.的错误. 最后通过从网上检索找到了一个答案: 可以同时解决掉在Ubuntu上和CentOS上检出失败的问题. 在Windows注册表中加入注册项: 32位机器: [HKEY_LOCAL_MACHINE\SOFTWARE\VisualSVN\VisualSVN Serv

解决Linux下乱码

1,设置Xshell编码为utf8 2,修改~/.bash_profile,添加 ? 1 export LANG=zh_CN.utf8 执行命令 ? 1 $source ~/.bash_profile 解决~ 解决Linux下乱码,布布扣,bubuko.com

解决Linux下Tomcat日志目录下的catalina.log日志文件过大的问题

本文摘自:(http://blog.csdn.net/stevencn76/article/details/6246162) 分类: Java技术专区2011-03-13 12:25 5017人阅读 评论(1) 收藏 举报 tomcatlinux工具任务web 由于Tomcat在默认情况下会将没有经过配置的web应用所产生的日志输出已经其本身的日志内容都输出到这个文件中,那么随着时间的推移,这个文件的尺寸将会越来越大,当需要检查日志内容时间会导致文件难以打开,而且同时tomcat依旧在不断的向文

rlwrap: command not found和解决linux下sqlplus 提供浏览历史命令行的功能

rlwrap工具可以解决linux下sqlplus 提供浏览历史命令行的功能,和删除先前输入错误的字母等问题 1.安装 需要readline包 这个安装光盘就有 [[email protected] RedHat]# cd RPMS/[[email protected] RPMS]# rpm -Uvh readline*warning: readline-4.3-13.i386.rpm: V3 DSA signature: NOKEY, key ID db42a60eerror: Failed

解决linux下cocos2dx不能播放声音

cocos2dx2.2.1在linux下引用#include "SimpleAudioEngine.h",报错找不到该文件. 修改makefile文件,添加 SHAREDLIBS += -lcocosdenshion COCOS_LIBS +=$(LIB_DIR)/linux/release/libcocosdenshion.so 并将cocos2d-x-2.2.1/CocosDenshion/include目录下的SimpleAudioEngine.h和Export.h拷贝到ecli

如何解决linux下apache启动时httpd: apr_sockaddr_info_get() failed for 报错

今天在家里的RHLE5.5上安装apache的时候,先用user1用户./configure命令配置,然后才用root用户make && make install,结果apache起来的时候就报如下错误: httpd: apr_sockaddr_info_get() failed for bogon httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 fo

完美解决 Linux 下 Sublime Text 中文输入

首先,我参考了好几篇文章,都是蛮不错的,先列出来: sublime-text-imfix:首先推荐这个方法,最简单,但是在我的系统上有些问题.可用这个的强烈推荐用这个 完美解决 Linux 下 Sublime Text 中文输入:讲的比较明白,也可用参考. Ubuntu下Sublime Text 3解决无法输入中文的方法: 讲解的最清楚了,建议看看. 测试系统:Ubuntu 14.04 (理论上所有 Linux 发行版都通用) 输入法:Fcitx 4.2.6.1 Sublime Text 版本:

JAVA压缩 解压缩zip 并解决linux下中文乱码

1. [代码][Java]代码   1:再压缩前,要设置linux模式, 需要使用第三方ant-1.6.5.jar  如果是文件目录,则ZipEntry zipEntry=new ZipEntry(basePath + System.getProperties().getProperty("file.separator"));zipEntry.setUnixMode(755);//解决linux乱码 如果是文件,则 ZipEntry zipEntry=new ZipEntry(base

解决 linux下编译make文件报错&ldquo;/bin/bash^M: 坏的解释器:没有那个文件或目录&rdquo; 问题

PS背景:我在公司做sdk 的pc端开发,所以经常会在win下编译通过之后跑到linux下再运行一次已确保能支持多平台. 今儿在win下跑完一程序,然后放到linux下跑的时候,我用指令: [plain] view plain copy sudo ./build.sh 但是却没有任何反应.于是我换了指令,用 [plain] view plain copy chmod u+x build.sh ./build.sh 报错 "build.sh  /bin/bash^M: 坏的解释器:没有那个文件或目