Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Posts: 144
Registered: ‎03-15-2011
My Device: blackberry smart phone
My Carrier: Airtel
Accepted Solution

problem while decrypting password which was encrypted

[ Edited ]

hello all i am saving the encrypted password in the database. And decrypting the password to attach to the url. but while i am decrypting it give me exception BadPadding Exception. I have used this class to encrypt and decrypt the password.

 

public class CryptAes {
	
	// First create the AES key based on the bytes in secretKey using  keyLength bits as the length
    static AESKey keydec = new AESKey("A3$1E*81234567891111111111111111".getBytes() );
    static AESKey keyenc = new AESKey("A3$1E*81234567891111111111111111".getBytes() );
    static AESKey keyenc128 = new AESKey("A3Q1EF8123456789".getBytes());
    static AESKey keydec128 = new AESKey("A3Q1EF8123456789".getBytes());
    
    private static byte[] iv = { 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c,
        0x0d, 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c, 0x0d };
    
    public static byte[] plainText= new byte[10000];

 public static String AESEncryption(byte[] plainText) {
    	
    	String resultString = null;
    	
    	try {
    		
    		 AESEncryptorEngine engine = new AESEncryptorEngine( keyenc128 );
    	        
    		 CBCEncryptorEngine cengine=new CBCEncryptorEngine(engine, new InitializationVector(iv));
    	        PKCS5FormatterEngine fengine = new PKCS5FormatterEngine( engine );
    	        ByteArrayOutputStream output = new ByteArrayOutputStream();
    	        BlockEncryptor encryptor = new BlockEncryptor( fengine, output );

    	        encryptor.write(plainText);
    	        encryptor.close();
    	        byte[] encryptedData = output.toByteArray(); output.close();
    	        String st=new String(encryptedData);
    	       
    	        byte[] base64 = Base64OutputStream.encode(encryptedData, 0, encryptedData.length, false, false);

    	              //Base64Coder.encodeString(Byte.toString(plainText));
    	              resultString = new String(base64);
    	             
    	     
			
		} catch (CryptoException cryptoException) {
			// TODO: handle exception
			System.out.println("Exception is "+cryptoException.getMessage()+"And the exception is"+cryptoException.toString());
		}
		catch (CryptoTokenException e) {
			// TODO: handle exception
			System.out.println("Exception is "+e.getMessage()+"And the exception is"+e.toString());
		}catch (CryptoUnsupportedOperationException e) {
			// TODO: handle exception
			System.out.println("Exception is "+e.getMessage()+"And the exception is"+e.toString());
		}catch (IOException e) {
			// TODO: handle exception
			System.out.println("Exception is "+e.getMessage()+"And the exception is"+e.toString());
		}
		return resultString;
  }
    
    public static String AESDecryption(byte[] cipherText, int dataLength ) /*throws CryptoException, IOException, CryptoTokenException, CryptoUnsupportedOperationException*/ {      
    	
    	String reString = null;
    	try {
    		
    		ByteArrayInputStream in = new ByteArrayInputStream( cipherText, 0, dataLength );
        	
        	// Now create the block decryptor and pass in a new instance
            // of an AES decryptor engine with the specified block length        
        	BlockDecryptor cryptoStream = new BlockDecryptor(new AESDecryptorEngine( keydec128 ), in );        
        	byte[] T = new byte[dataLength];
            
        	// Read the decrypted text from the AES decryptor stream and        
        	// return the actual length read        
        	
        	int length = cryptoStream.read( T ); //Here i am getting exception BadPadding    
        	reString = new String(T);      
        	int i=reString.indexOf("</msg>");     
        	reString = reString.substring(0,i+6);      
			
		} catch (CryptoException e) {
			// TODO: handle exception
			System.out.println("Exception is ="+e.getMessage());
		}catch (CryptoTokenException e) {
			// TODO: handle exception
			System.out.println("Exception is ="+e.getMessage());
		}catch (CryptoUnsupportedOperationException e) {
			// TODO: handle exception
			System.out.println("Exception is ="+e.getMessage());
		}catch (IOException e) {
			// TODO: handle exception
			System.out.println("Exception is ="+e.getMessage()+"333333333333"+e.toString());
		}
    	// Create the input stream based on the ciphertext        
    	
		return reString;
    	
    }
    

 help me out from this.

Developer
Posts: 133
Registered: ‎04-30-2010
My Device: Curve 8520
My Carrier: T-Mobile

Re: problem while decrypting password which was encrypted

I just took a look at my crypt/decrypt classes, and I think that because you have used a PKCS5FormatterEngine to add padding in your encrpytion class, you then need to use a PKCS5Unformatter Engine in your decrypt class to remove the padding.  (I just noticed you removed your encrpyt class from your code sample - that didn't help when I reviewed your code to provide an answer, so I'm now working from memory)

Developer
Posts: 144
Registered: ‎03-15-2011
My Device: blackberry smart phone
My Carrier: Airtel

Re: problem while decrypting password which was encrypted

[ Edited ]

Question edited i have put that method there too. and how to use  PKCS5Unformatter Engine class. Please help

Developer
Posts: 133
Registered: ‎04-30-2010
My Device: Curve 8520
My Carrier: T-Mobile

Re: problem while decrypting password which was encrypted

Just reverse your encryption method. Create your AESdecryptor Engine, pass this to the PKCS5UnformatterEngine, and pass the result to your BlockDecryptor along with your encrypted data
Developer
Posts: 144
Registered: ‎03-15-2011
My Device: blackberry smart phone
My Carrier: Airtel

Re: problem while decrypting password which was encrypted

[ Edited ]

as i think there is no constructor  for PKCS5UnformatterEngine class which accept  AESdecryptorEngine . So it wont work Smiley Sad

Developer
Posts: 133
Registered: ‎04-30-2010
My Device: Curve 8520
My Carrier: T-Mobile

Re: problem while decrypting password which was encrypted

[ Edited ]

Have you actually tried it?

 

Here is my code: (though this is using TripleDES rather than AES)

 

TripleDESDecryptorEngine decryptorEngine = new TripleDESDecryptorEngine(tripleDESKey);

// Create the unformatter engine that will remove any of the
// padding bytes.
PKCS5UnformatterEngine unformatterEngine = new PKCS5UnformatterEngine( decryptorEngine );

// Set up an input stream to hand the encrypted data to the
// block decryptor.
ByteArrayInputStream inputStream = new ByteArrayInputStream(encryptedData);

// Create the block decryptor passing in the unformatter engine and
// the encrypted data.
BlockDecryptor decryptor = new BlockDecryptor( unformatterEngine, inputStream );

 

Developer
Posts: 144
Registered: ‎03-15-2011
My Device: blackberry smart phone
My Carrier: Airtel

Re: problem while decrypting password which was encrypted

i had used the sample code done by the TripleDES which i got from http://docs.blackberry.com/en/developers/deliverables/29302/CS_Encoding_a_message_using_TripleDES_15... it runs fine but when i integrated that into my app its throws me exception BadPadding Exception. Dont know why its happening. I will try it today again and see if it work. otherwise i will put my snippet of code here. 

Developer
Posts: 144
Registered: ‎03-15-2011
My Device: blackberry smart phone
My Carrier: Airtel

Re: problem while decrypting password which was encrypted

[ Edited ]

I was trying to do encrypt and decrypt by the way above but did not succeeded so i just change the way to encrypt or decrypt the password. I had just Use Base64Coder class to accomplish that. And thanks for your concern. And here is the class Base64Coder, if some one needs it.

//Copyright 2003-2009 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
//www.source-code.biz, www.inventec.ch/chdh
//
//This module is multi-licensed and may be used under the terms
//of any of the following licenses:
//
//EPL, Eclipse Public License, http://www.eclipse.org/legal
//LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html
//AL, Apache License, http://www.apache.org/licenses
//BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php
//
//Please contact the author if you need another license.
//This module is provided "as is", without warranties of any kind.


/**
* A Base64
* r/Decoder.
*
* <p>
* This class is used to encode and decode data in Base64 format as described in RFC 1521.
*
* <p>
* Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL/LGPL/AL/BSD.
*
* <p>
* Version history:<br>
* 2003-07-22 Christian d'Heureuse (chdh): Module created.<br>
* 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br>
* 2006-11-21 chdh:<br>
*  &nbsp; Method encode(String) renamed to encodeString(String).<br>
*  &nbsp; Method decode(String) renamed to decodeString(String).<br>
*  &nbsp; New method encode(byte[],int) added.<br>
*  &nbsp; New method decode(String) added.<br>
* 2009-07-16: Additional licenses (EPL/AL) added.<br>
* 2009-09-16: Additional license (BSD) added.<br>
*/


public class Base64Coder {


	//Mapping table from 6-bit nibbles to Base64 characters.

	private static char[]    map1 = new char[64];

	static {
   
		int i=0;  
		for (char c='A'; c<='Z'; c++) map1[i++] = c;  
		for (char c='a'; c<='z'; c++) map1[i++] = c;   
		for (char c='0'; c<='9'; c++) map1[i++] = c;
		map1[i++] = '+'; map1[i++] = '/';		
	}
	//Mapping table from Base64 characters to 6-bit nibbles.

	private static byte[]    map2 = new byte[128];

	static {  		
		for (int i=0; i<map2.length; i++) map2[i] = -1;				
		for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; 		
	}


	/**
	 * Encodes a string into Base64 format.
	 * No blanks or line breaks are inserted.
	 * @param s  a String to be encoded.
	 * @return   A String with the Base64 encoded data.
	 */

	public static String encodeString (String s) {		
		
		return new String(encode(s.getBytes())); 
		
	}

	/**
	 * Encodes a byte array into Base64 format.
	 * No blanks or line breaks are inserted.
	 * @param in  an array containing the data bytes to be encoded.
	 * @return    A character array with the Base64 encoded data.
	 */

	
	public static char[] encode (byte[] in) {
		
		return encode(in,in.length); 
		
	}

	/**
	 * Encodes a byte array into Base64 format.
	 * No blanks or line breaks are inserted.
	 * @param in   an array containing the data bytes to be encoded.
	 * @param iLen number of bytes to process in <code>in</code>.
	 * @return     A character array with the Base64 encoded data.
	 */

	public static char[] encode (byte[] in, int iLen) {

		int oDataLen = (iLen*4+2)/3;       // output length without padding
		int oLen = ((iLen+2)/3)*4;         // output length including padding
		char[] out = new char[oLen];
		int ip = 0;
		int op = 0;

		while (ip < iLen) {
			int i0 = in[ip++] & 0xff;  
			int i1 = ip < iLen ? in[ip++] & 0xff : 0;  
			int i2 = ip < iLen ? in[ip++] & 0xff : 0;  
			int o0 = i0 >>> 2; 
			int o1 = ((i0 &   3) << 4) | (i1 >>> 4);   
			int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);   
			int o3 = i2 & 0x3F;
			
			out[op++] = map1[o0];  
			out[op++] = map1[o1];   
			out[op] = op < oDataLen ? map1[o2] : '='; op++;   
			out[op] = op < oDataLen ? map1[o3] : '='; op++; 			
		}
		
		return out; 		
	}

	/**
	 * Decodes a string from Base64 format.
	 * @param s  a Base64 String to be decoded.
	 * @return   A String containing the decoded data.
	 * @throws   IllegalArgumentException if the input is not valid Base64 encoded data.
	 */

	public static String decodeString (String s) {
		return new String(decode(s));
	}

	/**
	 * Decodes a byte array from Base64 format.
	 * @param a Base64 String to be decoded.
	 * @return   An array containing the decoded data bytes.
	 * @throws   IllegalArgumentException if the input is not valid Base64 encoded data.
	 */

	public static byte[] decode (String s) {
		return decode(s.toCharArray()); 		
	}

	/**
	 * Decodes a byte array from Base64 format.
	 * No blanks or line breaks are allowed within the Base64 encoded data.
	 * @param in  a character array containing the Base64 encoded data.
	 * @return    An array containing the decoded data bytes.
	 * @throws    IllegalArgumentException if the input is not valid Base64 encoded data.
	 */

	public static byte[] decode (char[] in) {

		int iLen = in.length;

		if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");

		while (iLen > 0 && in[iLen-1] == '=') iLen--;

		int oLen = (iLen*3) / 4;

		byte[] out = new byte[oLen];

		int ip = 0;

		int op = 0;

		while (ip < iLen) {
   
			int i0 = in[ip++];
   
			int i1 = in[ip++];
   
			int i2 = ip < iLen ? in[ip++] : 'A';
   
			int i3 = ip < iLen ? in[ip++] : 'A';
   
			if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
      
				throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
   
			int b0 = map2[i0];
   
			int b1 = map2[i1];
   
			int b2 = map2[i2];
   
			int b3 = map2[i3];
   
			if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
      
				throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
  
			int o0 = ( b0       <<2) | (b1>>>4);
   
			int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
   
			int o2 = ((b2 &   3)<<6) |  b3;
  
			out[op++] = (byte)o0;
   
			if (op<oLen) out[op++] = (byte)o1;
   
			if (op<oLen) out[op++] = (byte)o2; }

		return out; 
		
	}


	//Dummy constructor.

	private Base64Coder() {}


} // end class Base64Coder