Linux running Java des decryption failed, reported Javax.crypto.BadPaddingException:Given final block not properly Padded__java

Source: Internet
Author: User
Tags base64 static class

The

DES Java source code is as follows:

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 encryption * @param plaindata * @param secretkey * @return * @throws Exception/public String encryption (S
		Tring Plaindata, String secretkey) throws exception{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 {//To prevent decryption times javax.crypto.IllegalBlockSizeException:Input length must Be multiple of the 8 when decrypting with padded cipher exception,//cannot convert the encrypted byte array directly to the string 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 decryption * @param secretdata * @param secretkey * @return * @throws Exception/Public Strin
		G Decryption (String secretdata, String secretkey) throws exception{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); }/** * Obtain secret key * * @param secretkey * @return * @throws nosuchalgorithmexception * * Private SECRETK EY GenerateKey (String secretkey) throws nosuchalgorithmexception{securerandom securerandom = new SecureRandom (secretKe
				
		Y.getbytes ());
		Generates a Keygenerator object for our chosen des algorithm keygenerator kg = null;
		try {kg = keygenerator.getinstance (des_algorithm); catch (NosuchalgoriThmexception e) {} kg.init (securerandom);
		
		Kg.init (SecureRandom);
	Generate key 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 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
		0123456789+/= ". 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) (+ I-' a ');
			for (int i = ' 0 '; I <= ' 9 '; i++) codes[i] = (byte) (+ I-' 0 ');
			codes[' + '] = 62;
codes['/'] = 63;		/** * Encodes raw data as base64 encoding */static public String encode (byte[] data) {char[] out = new char[(Data.leng
			TH + 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 to New String (out); /** * Decodes base64 encoded data into raw data */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;
 }
	}
}


This code works properly under Windows and can be decrypted properly after encrypted ciphertext. The results of the operation are as follows:

xl1neww4mm09evmy3tetbng8hsftfeboilhnt7ubkbg=
cy11xlbrmzyh:604:301:1353064296

But to run on Linux, the error message, the following image:

As you can see in the picture, the same plaintext (cy11xlbrmzyh:604:301:1353064296) is encrypted, and the result of encrypting on Linux is different from that on Windows, and it is not possible to decrypt encrypted ciphertext after encryption and throw an exception on Linux.

cause: After checking, locate the method that generates the key, that is, the following red code:

/** *
	 access to secret key
	 * * 
	 @param secretkey
	 * @return
	 * @throws nosuchalgorithmexception
	* * Private Secretkey GenerateKey (String secretkey) throws nosuchalgorithmexception{securerandom
		= new SecureRandom (Secretkey.getbytes ()); The main is here Code
				
		//For our chosen des algorithm to generate a Keygenerator object
		keygenerator kg = null;
		try {
			kg = keygenerator.getinstance (des_algorithm);
		} catch (NoSuchAlgorithmException e) {
		}
		Kg.init (securerandom);
		Kg.init (securerandom);
		
		Generate Key return
		Kg.generatekey ();
	}

The SecureRandom implementation is entirely in the internal state of the operating system itself, unless the caller is calling the GetInstance method and then invoking the Setseed method, which is the same for each generated key on Windows, but in Solaris or part of the Linux system On the other hand. For a detailed introduction to the SecureRandom class, see http://yangzb.iteye.com/blog/325264

Solutions

Method 1: The red part of the original GenerateKey method is red as follows:

	/** *
	 access to secret key
	 * * 
	 @param secretkey
	 * @return
	 * @throws nosuchalgorithmexception
	* * Private Secretkey GenerateKey (String secretkey) throws nosuchalgorithmexception{
		//Prevent random generation key
		under Linux SecureRandom securerandom = securerandom.getinstance ("sha1prng");
		Securerandom.setseed (Secretkey.getbytes ());
		
		Generates a Keygenerator object for our chosen des algorithm
		keygenerator kg = null;
		try {
			kg = keygenerator.getinstance (des_algorithm);
		} catch (NoSuchAlgorithmException e) {
		}
		Kg.init (securerandom);
		Kg.init (securerandom);
		
		Generate Key return
		Kg.generatekey ();
	}


Method 2: Instead of using securerandom to generate Secretkey, use secretkeyfactory; re-implement method GenerateKey with the following code

	/** *
	 Obtain key
	 * * 
	 @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);
	}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.