java.lang.IllegalArgumentException: bad base-64 when decrypting string - encryption

I am trying to encrypt a string using the KeyStore and used this post as reference.
KeyPairGeneratorSpec replacement with KeyGenParameterSpec.Builder equivalents - Keystore operation failed
yet, I keep getting this "bad base-64" when I decrypt the string. I am not understanding exactly how to fix this. I understand that the encrypted string contains characters that the decryptor does not know. But I don't understand the fix.
I saw some posts like those, but did not help much since there is no code on the answers.
java.lang.IllegalArgumentException: bad base-64
This is a snipped of my the test code, can someone show me how I decrpyt my string?
Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
inCipher.init(Cipher.ENCRYPT_MODE, publicKey);
Cipher outCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
outCipher.init(Cipher.DECRYPT_MODE, privateKey);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(
outputStream, inCipher);
cipherOutputStream.write(plainText.getBytes("UTF-8"));
cipherOutputStream.close();
String ecryptedText = outputStream.toString();
Log.d(TAG, "Encrypt = " + ecryptedText);
String cipherText = ecryptedText;
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), outCipher);
ArrayList<Byte> values = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
values.add((byte)nextByte);
}
byte[] bytes = new byte[values.size()];
for(int i = 0; i < bytes.length; i++) {
bytes[i] = values.get(i).byteValue();
}
String finalText = new String(bytes, 0, bytes.length, "UTF-8");
Log.d(TAG, "Decrypt = " + ecryptedText);

Here is a working example on how you can use Android KeyStore to Encrypt/Decrypt memory strings by using ByteArrayOutputStream and ByteArrayInputStream. Notice the provider change, for >= 6 use "AndroidKeyStoreBCWorkaround" and for older versions use "AndroidOpenSSL". Also, you have to encode the encrypted data to Base64 string using Base64.encodeToString like this:
String ecryptedText = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
My final working example based on your code
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(
"key1",
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.build());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// error in android 6: InvalidKeyException: Need RSA private or public key AndroidOpenSSL
// error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
String provider = Build.VERSION.SDK_INT < Build.VERSION_CODES.M ? "AndroidOpenSSL" : "AndroidKeyStoreBCWorkaround";
Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
inCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
Cipher outCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
outCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(
outputStream, inCipher);
String plainText = "This is a text";
cipherOutputStream.write(plainText.getBytes("UTF-8"));
cipherOutputStream.close();
String ecryptedText = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
Log.d(TAG, "Encrypt = " + ecryptedText);
String cipherText = ecryptedText;
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), outCipher);
ArrayList<Byte> values = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
values.add((byte)nextByte);
}
byte[] bytes = new byte[values.size()];
for(int i = 0; i < bytes.length; i++) {
bytes[i] = values.get(i).byteValue();
}
String finalText = new String(bytes, 0, bytes.length, "UTF-8");
Log.d(TAG, "Decrypt = " + finalText);
} catch (javax.crypto.NoSuchPaddingException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchProviderException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidKeyException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (UnsupportedOperationException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
OUTPUTS
D/MainActivity: Encrypt = rejkfeas3HgYnZOlC4S/R3KvlMTyiBjr5T6LqWGj9bq6nvpM0KBsoeYtr4OdCLITFX5GojuO4VpB
Hy11n8zc9JcAx4IFW0Aw0/DfCmMDvIomQItBAaIWewZqNHc0UwS0y/JRhAe8SiTz5sFJ6Abvgax6
vEfbYT0gzok+qtlfBNQLPvXejquhc0pZBaX1RgKDZyEJh3DBVRaFDgogK8XphaI/xtd1Cww9uO63
QxA7HfrFUN8rJXrHF4EMi/yrDxs2xVHGF0v21xeuXRwLW9JXYn4fFAJJ0Jr8N5f03UDuKeNlI568
RFVOGH7WpOLvKN4CDlsC+DT4Z8YVIOdtS/tO+Q==
D/MainActivity: Decrypt = This is a text
UPDATE
For Android API 19, you just have to use the previous KeyStore API KeyPairGeneratorSpec instead of KeyGenParameterSpec like this:
try {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 1);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(this)
.setAlias("key1")
.setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
generator.initialize(spec);
// error in android 6: InvalidKeyException: Need RSA private or public key AndroidOpenSSL
// error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
String provider = Build.VERSION.SDK_INT < Build.VERSION_CODES.M ? "AndroidOpenSSL" : "AndroidKeyStoreBCWorkaround";
KeyPair keyPair = generator.generateKeyPair();
Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
inCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
Cipher outCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
outCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(
outputStream, inCipher);
String plainText = "This is a text";
cipherOutputStream.write(plainText.getBytes("UTF-8"));
cipherOutputStream.close();
String ecryptedText = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
Log.d(TAG, "Encrypt = " + ecryptedText);
String cipherText = ecryptedText;
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), outCipher);
ArrayList<Byte> values = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
values.add((byte)nextByte);
}
byte[] bytes = new byte[values.size()];
for(int i = 0; i < bytes.length; i++) {
bytes[i] = values.get(i).byteValue();
}
String finalText = new String(bytes, 0, bytes.length, "UTF-8");
Log.d(TAG, "Decrypt = " + finalText);
} catch (javax.crypto.NoSuchPaddingException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchProviderException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidKeyException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (UnsupportedOperationException e) {
Log.e(TAG, Log.getStackTraceString(e));
}

Related

AES 256 Encryption Decryption,

Decryption logic is missing something can you please assist.
Output is not completely decrypted.
Java Encryption Logic:
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
try {
String in ="This is a text message";
byte[] input = in.toString().getBytes("utf-8");
String ENCRYPTION_KEY = "RW50ZXIgS2V5IEhlcmU=";
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));
// SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skc);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
// String query = Base64.encodeToString(cipherText, Base64.DEFAULT);
String query = new String(java.util.Base64.getEncoder().encode(cipherText));
System.out.println("query " + query);
// String query = new String(encode(cipherText), StandardCharsets.ISO_8859_1);
} catch(UnsupportedEncodingException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
Nodejs Decryption Logic:
let crypto = require('crypto');
var decipher = crypto.createDecipher('aes-256-ecb', "RW50ZXIgS2V5IEhlcmU=");
decipher.setAutoPadding(false);
console.log(decipher.update("EncyptedText", 'base64', 'utf8') + decipher.final('utf8'));

How to translate CryptoJS AES into java code

I want to translate CryptoJS code into java code .This is the javascript code:
CryptoJS.AES.encrypt('hello',CryptoJS.enc.Utf8.parse(CryptoJS.MD5("http://stackoverflow.com")), {iv: CryptoJS.enc.Utf8.parse("1234567812345678")})
Above the code result invoke to string is 'QtzDsbCgmA9+XBVEsEm70w=='
Then I get the key value by CryptoJS.MD5("http://stackoverflow.com").toString() method(key = 57f4dad48e7a4f7cd171c654226feb5a)
This is the java code:
try {
String content = "hello";
String key = "57f4dad48e7a4f7cd171c654226feb5a";
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes("utf-8")));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key1 = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key1,new IvParameterSpec("1234567812345678".getBytes("UTF-8")));
byte[] result = cipher.doFinal(byteContent);
System.out.println(new String(result).equals("QtzDsbCgmA9+XBVEsEm70w=="));
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
but the output result is false.How to fix the java code to change the result to true.
According to #Luka Park advice,I have solve to my question.This is my solution:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);

Write data from Derby to JavaFX TableView

I'm new to JavaDb/Derby.I'm migrating a project from MySQL to Derby (Project made with JavaFX).I have created an Embedded Db under NetBeans. GUI has Serial Number field (textfield), Name field (textfield), ImageView and TableView (columns with respective data). Below is the java code for connecting with Derby.
public static Connection ConnectionDb() {
try{
String url = "jdbc:derby:Test_JavaDb/webdb;create=true";
String user = "root";
String password = "root";
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("Connected to database #1");
}
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return null;
}
//BELOW METHOD IS LINKED TO A BUTTON FOR LOADING TABLE
#FXML public void LoadTable(){
data.clear();
try{
conn = lrconn.ConnectionDb();
String sql = "select * from TEST";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
data.add(new TestPOJO(
rs.getString(1),
rs.getString(2),
rs.getString(3)));
Table.setItems(data);
}
pst.close();
rs.close();
}catch(Exception e1){
}
Table.setOnMouseClicked((MouseEvent me) -> {
try {
conn = lrconn.ConnectionDb();
TestPOJO user = (TestPOJO) Table.getSelectionModel().getSelectedItem();
String sql = "select * from TEST where SLNO =?";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getSLNO());
rs = pst.executeQuery();
while (rs.next()) {
slnoField.setText(rs.getString(1));
nameField.setText(rs.getString(2));
try (InputStream is = rs.getBinaryStream(3)) {
OutputStream os = new FileOutputStream(new File("photo1.jpg"));
byte[] content = new byte[1024];
int size = 0;
while((size= is.read(content))!=-1){
os.write(content,0,size);
}
os.close();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
image1 = new Image("file:photo1.jpg");
imgvw.setImage(image1);
rs.close();
pst.close();
}catch (SQLException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
});
Table.setOnKeyReleased((KeyEvent e) -> {
if(e.getCode()== KeyCode.UP || e.getCode() == KeyCode.DOWN){
try {
TestPOJO user = (TestPOJO) Table.getSelectionModel().getSelectedItem();
String sql = "select * from TEST where SLNO =?";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getSLNO());
rs = pst.executeQuery();
while (rs.next()) {
slnoField.setText(rs.getString(1));
nameField.setText(rs.getString(2));
try (InputStream is = rs.getBinaryStream(3)) {
OutputStream os = new FileOutputStream(new File("photo1.jpg"));
byte[] content = new byte[1024];
int size = 0;
while((size= is.read(content))!=-1){
os.write(content,0,size);
}os.close();
}
image1 = new Image("file:photo1.jpg");
imgvw.setImage(image1);
}}catch (FileNotFoundException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | SQLException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
The connection works as I get the output "Connected to database #1" on executing code (Clicking on LOAD TABLE BUTTON). But GUI table does not get updated with data from the Embedded Database. Please help.

Encryption / decryption for j2me app with AES 128 encryption using sha256 hashing

I have to use encryption / decryption mechanism for a j2me application and lots of searching I found that Bouncy Castle is most suitable for j2me apps.
Below are the steps that I follow to perform encryption:
Get a string needed to create a hash key using sha256 algorithm;
With that hash key perform AES-128 encryption for a plain text.
Below is the sample code. It is using key and IV (Initialization Vector) for encryption key generation. Is it same as sha256 hashing?
static String strEnc = "String for encryption";
final static String strPassword = "2345678978787878"; // AES 128 -
String encrypted;
public static String strEncResult;
public static String strDcrResult;
public static String keyStr;
String dcrtpt;
String enc1;
//Key key;
/*public static byte[] getSHA256(String key) {
SHA256Digest digester = new SHA256Digest();
byte[] retValue = new byte[digester.getDigestSize()];
digester.update(key.getBytes(), 0, key.length());
digester.doFinal(retValue, 0);
System.out.println("retValue === "+retValue);
return retValue;
}*/
public static byte[] cipherData(PaddedBufferedBlockCipher cipher,
byte[] data) throws Exception {
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv)
throws Exception {
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
iv);
aes.init(false, ivAndKey);
return cipherData(aes, cipher);
}
public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv)
throws Exception {
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
iv);
aes.init(true, ivAndKey);
return cipherData(aes, plain);
}
public static String encryptMe(String plain){
byte[] plainStr = plain.getBytes();
byte[] keyStr = strPassword.getBytes();//getSHA256(strPassword);
byte[] ivStr = strPassword.getBytes();//getSHA256(strPassword);
try {
byte[] encBytes = encrypt(plainStr, keyStr,
ivStr);
byte[] encbase = Base64.encode(encBytes);
strEncResult = new String(encbase, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return strEncResult;
}
public static String decryptMe(String encrtptedStr){
try {
byte[] dcrByte = Base64.decode(encrtptedStr.getBytes());
byte[] dec = decrypt(dcrByte, strPassword.getBytes()/*getSHA256(strPassword)*/,
strPassword.getBytes()/*getSHA256(strPassword)*/);
strDcrResult = new String(dec, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return strDcrResult;
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
byte[] enc;
try {
enc = encrypt(strEnc.getBytes(), /*getSHA256(strPassword)*/strPassword.getBytes(),
/*getSHA256(strPassword)*/strPassword.getBytes());
byte[] encbase = Base64.encode(enc);
encrypted = new String(encbase, "UTF-8");
enc1= encryptMe ("String for encryption");
System.out.println("Encrypted is:" + encbase + "/// "+enc1);
} catch (Exception e) {
e.printStackTrace();
}
byte[] decbase = Base64.decode(encrypted.getBytes());
byte[] dec;
try {
dec = decrypt(decbase, /*getSHA256(strPassword)*/strPassword.getBytes(),
/*getSHA256(strPassword)*/strPassword.getBytes());
dcrtpt = decryptMe(enc1);
System.out.println("Decrypted file is:" + new String(dec, "UTF-8")+"///"+dcrtpt);
} catch (Exception e) {
e.printStackTrace();
}
}
i got it worked!!. i have used sha256 for secret key generation and took first 16 digit for AES 128 encryption. i am getting correct encrypted and decrypted data when it is 16 or below 16 string. if it is above 16 char string i am getting 16 char with some unwanted characters. (Eg: abcdefghijklmnop5#�D�!�&M�\~C��) can anybody help me to sort this issue. please see below for code
public static String getSHA256(String key) {
SHA256Digest digester = new SHA256Digest();
byte[] retValue = new byte[digester.getDigestSize()];
digester.update(key.getBytes(), 0, key.length());
digester.doFinal(retValue,0);
byteToStr = new String(Hex.encode(retValue));
System.out.println("byteToStr === " + byteToStr);
byteToStr = byteToStr.substring(0, 16);
System.out.println("byteToStr after subString === " + byteToStr);
return byteToStr;
}
public static byte[] cipherData(BufferedBlockCipher cipher, byte[] data)
throws Exception {
int minSize = cipher.getOutputSize(data.length);
System.out.println("min Size = "+minSize);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
System.out.println("length1 = "+length1 +"/ length2 = "+length2);
int actualLength = length1 + length2;
System.out.println("actualLength = "+actualLength);
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
public static byte[] decrypt(byte[] cipher, byte[] key/* , byte[] iv */)
throws Exception {
/*
* PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new
* CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new
* ParametersWithIV(new KeyParameter(key), iv); aes.init(false,
* ivAndKey); return cipherData(aes, cipher);
*/
BufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()));
KeyParameter secretKey = new KeyParameter(key);
aes.init(false, secretKey);
return cipherData(aes, cipher);
}
public static byte[] encrypt(byte[] plain, byte[] key/* , byte[] iv */)
throws Exception {
/*
* PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new
* CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new
* ParametersWithIV(new KeyParameter(key), iv);
*/
BufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()));
KeyParameter secretKey = new KeyParameter(key);
aes.init(true, secretKey);
return cipherData(aes, plain);
}
public static String encryptMe(String plain) {
byte[] plainStr = plain.getBytes();
byte[] keyStr = getSHA256(key).getBytes();
// byte[] ivStr = iv.getBytes();//
System.out.println("key str = "+Strings.fromByteArray(keyStr));
try {
byte[] encBytes = encrypt(plainStr, keyStr/*
* , ivStr
*/);
strEncResult= Base64.toBase64String(encBytes);
//strEncResult = new String(encbase);
} catch (Exception e) {
e.printStackTrace();
}
return strEncResult;
}
public static String decryptMe(String cipherText) {
try {
byte[] dcrByte = Base64.decode(cipherText);
byte[] dec = decrypt(dcrByte, getSHA256(key).getBytes()/*
* ,iv.getBytes
* ()
*/);
strDcrResult = Strings.fromByteArray(dec);
} catch (Exception e) {
e.printStackTrace();
}
return strDcrResult;
}

blackberry HttpConnection.GET

URL: http://monSite/GET.asp
we must authenticate before getting the result.
I want to send the login and password with HttpConn.setRequestMethod (HttpConnection.POST) and retrieve the XML file with HttpConn.setRequestMethod (HttpConnection.GET) with the same HTTP Client.
conn = (HttpConnection) new ConnectionFactory().getConnection(_url).getConnection();
URLEncodedPostData postData = null;
postData = new URLEncodedPostData("UTF-8", false);
postData.append("userName",_username);
postData.append("passWord", _password);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LANGUAGE, "en-US");
conn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
// Specify the content type.
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, postData.getContentType());
byte [] postBytes = postData.getBytes();
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
os = conn.openOutputStream();
os.write(postBytes);
os.flush();
os.close();
//GET XML file
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
int total = 0;
int size = 1024;
char[] buffer = new char[size];
int len;
InputStreamReader isr = new InputStreamReader(conn.openInputStream(), "UTF-8");
while ((len = isr.read(buffer, 0, size)) > 0)
{
buff.append(buffer, 0, len);
total += len;
}
result = buff.toString();
} else {
result = "Error in connection" + conn.getResponseCode();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the HttpConnection.POST works very well but GET no (login failed: the authentication parameter does not saved)
In HttpConnection.GET request you need to append attribute in your url like:
String url="http://www.xyz?userName="+_username+"&password="+_password+"";
and then get the InputStream
below link may be helpful for you
http://supportforums.blackberry.com/t5/Java-Development/Make-an-HTTP-Connection-to-get-a-Content-of-URL/td-p/95075

Resources