`
slikel
  • 浏览: 65659 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Linux下运行java DES解密失败,报javax.crypto.BadPaddingException:Given final block not pro

 
阅读更多
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

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.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DESEncryptTest {
private static final String DES_ALGORITHM = "DES";
		
	/**
	 * DES加密
	 * @param plainData
	 * @param secretKey
	 * @return
	 * @throws Exception
	 */
	public String encryption(String plainData, String secretKey) throws Exception{

		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance(DES_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, generateKey(secretKey));
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}catch(InvalidKeyException e){
			
		}
		
		try {
			// 为了防止解密时报javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher异常,
			// 不能把加密后的字节数组直接转换成字符串
			byte[] buf = cipher.doFinal(plainData.getBytes());
			
			return Base64Utils.encode(buf);
			
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			throw new Exception("IllegalBlockSizeException", e);
		} catch (BadPaddingException e) {
			e.printStackTrace();
			throw new Exception("BadPaddingException", e);
		}
	    
	}

	/**
	 * DES解密
	 * @param secretData
	 * @param secretKey
	 * @return
	 * @throws Exception
	 */
	public String decryption(String secretData, String secretKey) throws Exception{
		
		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance(DES_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey));
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new Exception("NoSuchAlgorithmException", e);
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			throw new Exception("NoSuchPaddingException", e);
		}catch(InvalidKeyException e){
			e.printStackTrace();
			throw new Exception("InvalidKeyException", e);
			
		}
		
		try {
			
			byte[] buf = cipher.doFinal(Base64Utils.decode(secretData.toCharArray()));
			
			return new String(buf);
			
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			throw new Exception("IllegalBlockSizeException", e);
		} catch (BadPaddingException e) {
			e.printStackTrace();
			throw new Exception("BadPaddingException", e);
		}
	}
	
	
	/**
	 * 获得秘密密钥
	 * 
	 * @param secretKey
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{
		SecureRandom secureRandom = new SecureRandom(secretKey.getBytes());
				
		// 为我们选择的DES算法生成一个KeyGenerator对象
		KeyGenerator kg = null;
		try {
			kg = KeyGenerator.getInstance(DES_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
		}
		kg.init(secureRandom);
		//kg.init(56, secureRandom);
		
		// 生成密钥
		return kg.generateKey();
	}
			
	public static void main(String[] a) throws Exception{
		String input = "cy11Xlbrmzyh:604:301:1353064296";
		String key = "37d5aed075525d4fa0fe635231cba447";
		
		DESEncryptTest des = new DESEncryptTest();
		
		String result = des.encryption(input, key);
		System.out.println(result);
		
		System.out.println(des.decryption(result, key));
			
	}
		
	static class Base64Utils {

		static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
		static private byte[] codes = new byte[256];
		static {
			for (int i = 0; i < 256; i++)
				codes[i] = -1;
			for (int i = 'A'; i <= 'Z'; i++)
				codes[i] = (byte) (i - 'A');
			for (int i = 'a'; i <= 'z'; i++)
				codes[i] = (byte) (26 + i - 'a');
			for (int i = '0'; i <= '9'; i++)
				codes[i] = (byte) (52 + i - '0');
			codes['+'] = 62;
			codes['/'] = 63;
		}
		
		/**
		 * 将原始数据编码为base64编码
		 */
		static public String encode(byte[] data) {
			char[] out = new char[((data.length + 2) / 3) * 4];
			for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
				boolean quad = false;
				boolean trip = false;
				int val = (0xFF & (int) data[i]);
				val <<= 8;
				if ((i + 1) < data.length) {
					val |= (0xFF & (int) data[i + 1]);
					trip = true;
				}
				val <<= 8;
				if ((i + 2) < data.length) {
					val |= (0xFF & (int) data[i + 2]);
					quad = true;
				}
				out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
				val >>= 6;
				out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
				val >>= 6;
				out[index + 1] = alphabet[val & 0x3F];
				val >>= 6;
				out[index + 0] = alphabet[val & 0x3F];
			}
			
			return new String(out);
		}

		/**
		 * 将base64编码的数据解码成原始数据
		 */
		static public byte[] decode(char[] data) {
			int len = ((data.length + 3) / 4) * 3;
			if (data.length > 0 && data[data.length - 1] == '=')
				--len;
			if (data.length > 1 && data[data.length - 2] == '=')
				--len;
			byte[] out = new byte[len];
			int shift = 0;
			int accum = 0;
			int index = 0;
			for (int ix = 0; ix < data.length; ix++) {
				int value = codes[data[ix] & 0xFF];
				if (value >= 0) {
					accum <<= 6;
					shift += 6;
					accum |= value;
					if (shift >= 8) {
						shift -= 8;
						out[index++] = (byte) ((accum >> shift) & 0xff);
					}
				}
			}
			if (index != out.length)
				throw new Error("miscalculated data length!");
			return out;
		}
	}
}


此代码在windows运行正常,对加密后的密文可以正常解密。运行结果如

xl1nEww4mm09EvMy3tETBNg8HSfTFeBoilhNT7uBKBg=
cy11Xlbrmzyh:604:301:1353064296

但是放到linux上运行,则报错,错误信息如图:

通过图片可以看到,对相同的明文(cy11Xlbrmzyh:604:301:1353064296)进行加密,在linux上加密后的结果和在windows上是不同的;而且在linux上不能对加密之后的密文进行解密,并抛出异常。

 

原因:
经过检查之后,定位在生成KEY的方法上,即如红色代码:
/**
	 * 获得秘密密钥
	 * 
	 * @param secretKey
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{
		SecureRandom secureRandom = new SecureRandom(secretKey.getBytes()); //主要是此处代码
				
		// 为我们选择的DES算法生成一个KeyGenerator对象
		KeyGenerator kg = null;
		try {
			kg = KeyGenerator.getInstance(DES_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
		}
		kg.init(secureRandom);
		//kg.init(56, secureRandom);
		
		// 生成密钥
		return kg.generateKey();
	}

SecureRandom   实现完全随操作系统本身的内部状态,除非调用方在   getInstance   方法,然后调用  setSeed   方法;该实现在   windows   上每次生成的   key   都相同,但是在   solaris   或部分   linux   系统上则不同。

 

解决办法

 方法1:把原来的generateKey方法中红色如的红色部分:

/**
	 * 获得秘密密钥
	 * 
	 * @param secretKey
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{
		//防止linux 随机生成key
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(secretKey.getBytes());
		
		// 为我们选择的DES算法生成一个KeyGenerator对象
		KeyGenerator kg = null;
		try {
			kg = KeyGenerator.getInstance(DES_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
		}
		kg.init(secureRandom);
		//kg.init(56, secureRandom);
		
		// 生成密钥
		return kg.generateKey();
	}


方法2: 不使用SecureRandom生成SecretKey,而是使用SecretKeyFactory;重新实现方法generateKey,代码如

/**
	 * 获得密钥
	 * 
	 * @param secretKey
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeyException 
	 * @throws InvalidKeySpecException 
	 */
	private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException,InvalidKeyException,InvalidKeySpecException{
		
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
		DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
		keyFactory.generateSecret(keySpec);
		return keyFactory.generateSecret(keySpec);
	}
分享到:
评论

相关推荐

    android DES加密解密 javax.crypto.IllegalBlockSizeException: last block incomplete in

    本话题将围绕在Android中使用DES加密和解密时遇到的一个常见问题展开:`javax.crypto.IllegalBlockSizeException: last block incomplete in decryption`。 这个异常通常发生在解密过程中,当输入的数据块大小与DES...

    javax.crypto crypto.jar

    javax.crypto.Cipher; javax.crypto.KeyGenerator; javax.crypto.spec.SecretKeySpec等

    jar.zip解决The import javax.crypto cannot be resolved

    5. **验证**:最后,尝试再次导入`javax.crypto`包并运行程序,确认错误是否已经消除。 在某些情况下,如果你的项目是Maven或Gradle项目,你可能需要在`pom.xml`或`build.gradle`文件中添加对应的依赖,确保在编译...

    解决Linux操作系统下AES解密失败的问题

    javax.crypto.BadPaddingException: Given final block not properly padded at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at ...

    图片处理 javax.imageio.IIOException: Unsupported Image Type

    在Java编程环境中,图片处理是一项常见的任务,但有时可能会遇到“javax.imageio.IIOException: Unsupported Image Type”的错误。这个异常通常表示Java的`ImageIO`类库无法识别或支持所尝试读取或写入的图像格式。...

    AES加密DEMO(javax.crypto.Cipher NET实现)

    此外,`javax.crypto.Cipher`类在.NET Core中可能需要额外的引用或适配,因为它是Java平台的一部分,而在.NET中通常使用`System.Security.Cryptography.Aes`类。 总的来说,这个AES加密DEMO展示了如何在.NET环境中...

    javax-crypto.jar

    javax.crypto包提供了多种加密算法的实现,如AES(高级加密标准)、DES(数据加密标准)、RSA(公钥加密算法)等。这些算法在信息安全领域有着广泛的应用,如保护数据的隐私性、防止数据篡改等。 2. **密钥管理**...

    微信小程序解密遇到pad block corrupted

    "pad block corrupted"错误意味着在解密过程中,填充检查失败,可能的原因有以下几点: 1. **密钥错误**:使用了错误的密钥进行解密,导致解密后的数据无法正确校验填充。 2. **初始化向量(IV)问题**:在某些...

    javax.activation.UnsupportedDataTypeException: no object DCH for MIME type

    ORA-29532: Java call terminated by uncaught Java exception: javax.mail.MessagingException: IOException while sending message; nested exception is: javax.activation.UnsupportedDataTypeException: no ...

    javax.servlet-3.0.0.v201112011016-API文档-中文版.zip

    赠送jar包:javax.servlet-3.0.0.v201112011016.jar; 赠送原API文档:javax.servlet-3.0.0.v201112011016-javadoc.jar; 赠送源代码:javax.servlet-3.0.0.v201112011016-sources.jar; 赠送Maven依赖信息文件:...

    javax.servlet-3.0.0.v201112011016-API文档-中英对照版.zip

    赠送jar包:javax.servlet-3.0.0.v201112011016.jar; 赠送原API文档:javax.servlet-3.0.0.v201112011016-javadoc.jar; 赠送源代码:javax.servlet-3.0.0.v201112011016-sources.jar; 赠送Maven依赖信息文件:...

    AES加密(解决了windows下正常,linux报错的问题)

    windows上加解密正常,linux上加密正常,解密时发生 异常: javax.crypto.BadPaddingException: Given final block not properly padded

    javax.annotation-api-1.3.2-API文档-中文版.zip

    赠送jar包:javax.annotation-api-1.3.2.jar; 赠送原API文档:javax.annotation-api-1.3.2-javadoc.jar; 赠送源代码:javax.annotation-api-1.3.2-sources.jar; 赠送Maven依赖信息文件:javax.annotation-api-...

    javax.mail-1.5.6-API文档-中文版.zip

    赠送jar包:javax.mail-1.5.6.jar; 赠送原API文档:javax.mail-1.5.6-javadoc.jar; 赠送源代码:javax.mail-1.5.6-sources.jar; 赠送Maven依赖信息文件:javax.mail-1.5.6.pom; 包含翻译后的API文档:javax.mail...

    javax.servlet-api-3.1.0.jar中文文档.zip

    javax.servlet-api-***.jar中文文档.zip,java,javax.servlet-api-***.jar,javax.servlet,javax.servlet-api,***,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,javax,servlet,api,中文API文档,手册,开发...

    javax.naming.NamingException: Cannot create resource instance

    javax.naming.NamingException: Cannot create resource instance类加载异常,希望可以帮助跟我一样错误的人。

    javax.transaction-api-1.2-API文档-中文版.zip

    赠送jar包:javax.transaction-api-1.2.jar; 赠送原API文档:javax.transaction-api-1.2-javadoc.jar; 赠送源代码:javax.transaction-api-1.2-sources.jar; 赠送Maven依赖信息文件:javax.transaction-api-1.2....

    javax.servlet jar包---解决找不到javax.servlet.*等问题

    - 在传统的Java Web项目中,通常将`javax.servlet.jar`和`javax.servlet.jsp.jar`添加到项目的类路径中,这可以通过在`WEB-INF/lib`目录下放置这两个jar包实现。 - 使用Maven或Gradle等构建工具时,可以在pom.xml...

    java/javascript/iOS的AES加解密(AES/CBC/PKCS5Padding)

    本文将深入探讨AES加密,特别是使用CBC(Cipher Block Chaining,密码块链接)模式和PKCS5Padding填充方式,并在JavaScript、Java和iOS平台上实现这一加密过程。 **一、AES加密简介** AES是一种对称加密算法,由...

    bcprov加密库

    at javax.crypto.Cipher.getInstance(Cipher.java:656) at javax.crypto.Cipher.getInstance(Cipher.java:595) ... 12 more Caused by: java.util.jar.JarException: file:/opt/code/signal-Server-master/target...

Global site tag (gtag.js) - Google Analytics