Android to esp8266 decryption - android

i used the aes library in android studio to encrypt a string of data to send to an esp8266 in AP mode. i am able to get the encrypted value but not the correct decrypted value. i am still particularly new to this and the decryption code was obtained through chatgpt.
this is the code i used to send an encrypted 16 byte value
new Thread(new Runnable() {
#Override
public void run() {
byte[] key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
String data = "thats my kung fu";
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
Log.d("EncryptedData", Base64.encodeToString(encryptedData, Base64.DEFAULT));
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(40, TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("data", Base64.encodeToString(encryptedData, Base64.DEFAULT))
.build();
Request request = new Request.Builder()
.url("http://192.168.4.1/post")
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String myResponse = response.body().string();
Log.i("POST", myResponse);
Log.d("TAG", "data: " + data);
} else {
Log.d("POST", "response code: " + response.code() + " response message: " + response.message());
}
}
#Override
public void onFailure(okhttp3.Call call, IOException e) {
e.printStackTrace();
Log.e("TAG", "Post request failed");
}
});
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
InvalidKeyException |
IllegalBlockSizeException |
BadPaddingException e) {
e.printStackTrace();
}
}
}).start();
i am able to receive the encrypted value on the esp, which is hYRPznVRiPVGVV0NkOy4XpVPZPLk6G6e7oLSAhZoSJk=
this is the arduino code to decrypt the value:
#include <AES.h>
#include <AESLib.h>
#include <AES_config.h>
#include <xbase64.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
AES aes;
const char* ssid = "ESP8266-AP";
const char* password = "password";
const byte key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
void handlePost() {
String val = server.arg("data");
byte decrypted[val.length()];
aes.set_key(key, sizeof(key));
aes.decrypt((byte*)val.c_str(), decrypted);
String decryptedVal = String((char*)decrypted);
Serial.println("Received value: " + decryptedVal);
Serial.println("Encrypted value: " + val);
server.send(200, "text/plain", "Value Received");
}
void setup() {
//Set ESP as AP
Serial.begin(9600);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);
//Initialize server
server.begin();
server.on("/post", HTTP_POST, handlePost);
Serial.println("Server started");
}
void loop() {
server.handleClient();
}
this is my output:
Server started
Received value: *qz����5��2�k�D{��?�3�?���?�j #��?
Encrypted value: hYRPznVRiPVGVV0NkOy4XpVPZPLk6G6e7oLSAhZoSJk=
*received value is the supposedly decrypted value.

Related

Android Keystore with large data giving issue,we are using AES/GCM/NoPadding.After a particular range its throwing exception

I am facing issues when using AES/GCM/NoPadding, after a particular range its throwing exception and its not encrypting after a range of 65536.I have text length of 131072 , but the encryption is only happeing till 65536.
even tried the following as well,
AES/GCM/NoPadding
AES/CBC/pkcs7padding.but after a particular range it is throwing invalidexception.
**Note:**
If I use BouncyCastle provider it is working fine(encryption is happening). But when I use Android keystore with keyspec is not working.
even tried the following as well,
AES/GCM/NoPadding
AES/CBC/pkcs7padding.but after a particular range it is throwing invalidexception.
code:
public static EncryptCallBack encryptText(final byte[] textToEncrypt)
throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException,
NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
InvalidAlgorithmParameterException, SignatureException, BadPaddingException,
IllegalBlockSizeException {
EncryptCallBack encryptCallBack = new EncryptCallBack();
final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
/*Cipher update for Large data and Incremental Encryption */
byte[] encryptedValue = null;
byte[] input = textToEncrypt;
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = 0;
try {
ctLength = cipher.update(input, 0, input.length, cipherText, 0);
Log.d("Update ciper","Update"+ ctLength);
} catch (ShortBufferException e) {
e.printStackTrace();
}
try {
ctLength += cipher.doFinal(cipherText, ctLength);
} catch (ShortBufferException e) {
e.printStackTrace();
}
encryptedValue = cipherText;
Log.d("Encrypted data Length","Encyrptedlength :"+ encryptedValue.length);
/*Cipher update for Large data and Incremental Encryption */
encryptCallBack.setSpecIV(cipher.getIV());
encryptCallBack.setData(encryptedValue);
return encryptCallBack;
}
/*SecertKey*/
public static SecretKey getSecretKey() {
SecretKey key = null;
try {
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
keyStore.load(null);
} catch (KeyStoreException | CertificateException |
NoSuchAlgorithmException | IOException e) {
}
if (!keyStore.containsAlias("alias")) {
KeyGenerator keygen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder("alias", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build();
keygen.init(spec);
key = keygen.generateKey();
} else {
KeyStore.SecretKeyEntry keyEntry = (KeyStore.SecretKeyEntry) keyStore.getEntry("alias", null);
key = keyEntry.getSecretKey();
}
} catch (Exception e) {
}
return key;
}
public static String decryptText(final byte[] encryptedData, byte[] specIV)
throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException,
NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
final GCMParameterSpec spec = new GCMParameterSpec(128, specIV);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(),spec);
return new String(cipher.doFinal(encryptedData), "UTF-8");
}
if anyone come across this kind of situation. please assist.

AES Encryption of api string response returning extra characters at start

I am trying to decrypt API encrypted response. But the decryption process returning extra characters at the start and also missing a double-quoted characters of JSON format response key shown below:
private void setListener() {
btnDecode.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View v) {
decodeCode();
}
});
}
private void decodeCode() {
String response = "bk/qo1fYH3aKseRNcXq6FLn2ScpSTZDyse4YINiQV34XTb2mOV95sB8uBemWl9p6XSGVYga+K6/n3LyJEgiyAmijL+y/ahb1h0ehv1Ejej+uVWN4yXWUr4TOFz+78iU5A9+znSQXIQIo8ti9Z+ALpvu4lqrDo2hZbF0OKDxxgOjLF28NSrNpVo9eThaH33vFmYZUZ1zFj281g8ahj6wf0MuL0Ev9bsI9AhX4eW0rJZSacW2/xZH81EPxcojerCzGnALxVGlE/MzxLSieUMWRkxKxQZ/Ux6EhiJy6kTkS4iku1Uk/qQJglj22eiIPROpNARts2lOo09PdsgJZb3DKm+j16FKfEC+fpLykXqQ5shtcW/tB0Qer+XFNBHGblDMYBaVzqahunvzHQKaSu2vF+A==";
try {
String responseResult = encryptUtils.decrypt (response, "1234567891123456");
txtDecode.setText (responseResult);
} catch (GeneralSecurityException e) {
e.printStackTrace ();
} catch (IOException e) {
e.printStackTrace ();
}
}
Here in return I am getting some extra characters before actual string. Also the Response key in which the complete response exist has invalid syntax i.e Response key start double-quote is missing. Decrypted string getting is:
J`#TBBKE#FQResponse":"{\"access_token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IllhYm5lciIsIm5iZiI6MTU3MjUxNDI2MywiZXhwIjoxNTcyNTE2MDYzLCJpYXQiOjE1NzI1MTQyNjN9.w4cQcr4pT3hyGPW5MOS7QbWL64nvHBf97OJ8DQWDRRg\",\"badge_Id\":\"108817\"}","ResponseMessage":"Login Success"}
And this is my EncryptUtils class. In this I have tried NoPadding encryption also in decrypt method but didn't work for me:
public class EncryptUtils {
public String encrypt(String value, String key)
throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
{
byte[] value_bytes = value.getBytes("UTF-8");
byte[] key_bytes = getKeyBytes(key);
return Base64.encodeToString(encrypt(value_bytes, key_bytes, key_bytes), 0);
}
public byte[] encrypt(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2, byte[] paramArrayOfByte3)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
{
// setup AES cipher in CBC mode with PKCS #5 padding
Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// encrypt
localCipher.init(1, new SecretKeySpec (paramArrayOfByte2, "AES"), new IvParameterSpec (paramArrayOfByte3));
return localCipher.doFinal(paramArrayOfByte1);
}
public String decrypt(String value, String key)
throws GeneralSecurityException, IOException
{
byte[] value_bytes = Base64.decode(value, 0);
byte[] key_bytes = getKeyBytes(key);
return new String(decrypt(value_bytes, key_bytes, key_bytes), "UTF-8");
}
public byte[] decrypt(byte[] ArrayOfByte1, byte[] ArrayOfByte2, byte[] ArrayOfByte3)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
{
// setup AES cipher in CBC mode with PKCS #5 padding
Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// decrypt
localCipher.init(2, new SecretKeySpec(ArrayOfByte2, "AES"), new IvParameterSpec(ArrayOfByte3));
return localCipher.doFinal(ArrayOfByte1);
}
private byte[] getKeyBytes(String paramString)
throws UnsupportedEncodingException
{
byte[] arrayOfByte1 = new byte[16];
byte[] arrayOfByte2 = paramString.getBytes("UTF-8");
System.arraycopy(arrayOfByte2, 0, arrayOfByte1, 0, Math.min(arrayOfByte2.length, arrayOfByte1.length));
return arrayOfByte1;
}
}
Your assumption that the IV is a copy of the key appears to be incorrect. It appears that the IV is all zeros. You can confirm this by replacing this line in decrypt:
return new String(decrypt(value_bytes, key_bytes, key_bytes), "UTF-8");
with
return new String(decrypt(value_bytes, key_bytes, new byte[16]), "UTF-8");
The decryption result becomes
{"Status":true,"Response":"{\"access_token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IllhYm5lciIsIm5iZiI6MTU3MjUxNDI2MywiZXhwIjoxNTcyNTE2MDYzLCJpYXQiOjE1NzI1MTQyNjN9.w4cQcr4pT3hyGPW5MOS7QbWL64nvHBf97OJ8DQWDRRg\",\"badge_Id\":\"108817\"}","ResponseMessage":"Login Success"}

How to encrypt and decrypt the json string in android using key?

I am currently working on a drawing based project , i had stored the values as on json format and store in file , but i want encrypt the json by using the key and decrypt the json the by same key.
Stringify your json using String resultString = JSON.stringify() and encrypt your resultString using the following method
public class EncryptUtils {
public static SecretKey generateKey(String mySecret)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
return secret = new SecretKeySpec(mySecret.getBytes(), "AES");
}
public static byte[] encryptMsg(String message, SecretKey secret)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
/* Encrypt the message. */
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
return cipherText;
}
public static String decryptMsg(byte[] cipherText, SecretKey secret)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException
{
/* Decrypt the message, given derived encContentValues and initialization vector. */
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret);
String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
return decryptString;
}
}
String mySecret="mySecretKeyString";
String secretKey = EncryptUtils.generateKey(mySecret);
String encryptedStr = EncryptUtils.encryptMsg(jsonResultString, secretKey));
String decryptedStr = EncryptUtils.decryptMsg(encryptedStr.getBytes("UTF-8"), secretKey));
finally you could get the JSON data using following method
try {
JSONObject obj = new JSONObject(decryptedString);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
Do not use this as some kind of security measurement.
The encryption mechanism in this post is a One-time pad, which means that the secret key can be easily recovered by an attacker using 2 encrypted messages. XOR 2 encrypted messages and you get the key. That simple!
public class EncryptUtils {
public static final String DEFAULT_ENCODING = "UTF-8";
static BASE64Encoder enc = new BASE64Encoder();
static BASE64Decoder dec = new BASE64Decoder();
public static String base64encode(String text) {
try {
return enc.encode(text.getBytes(DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
return null;
}
}//base64encode
public static String base64decode(String text) {
try {
return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
} catch (IOException e) {
return null;
}
}//base64decode
public static void main(String[] args) {
String txt = "some text to be encrypted";
String key = "key phrase used for XOR-ing";
System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));
String encoded = base64encode(txt);
System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
}
public static String xorMessage(String message, String key) {
try {
if (message == null || key == null) return null;
char[] keys = key.toCharArray();
char[] mesg = message.toCharArray();
int ml = mesg.length;
int kl = keys.length;
char[] newmsg = new char[ml];
for (int i = 0; i < ml; i++) {
newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
}//for i
return new String(newmsg);
} catch (Exception e) {
return null;
}
}//xorMessage
}

How to do RSA encryption for IOS using Ionic

I'm developing a native android app and hybrid IOS app. I'm encrypting the password before sending the request to BL. Below is my native code.
public String Encrypt (String plain) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
try {
AssetManager assets = context.getAssets();
byte[] key = readFully(
assets.open("encryption.der", AssetManager.ACCESS_BUFFER));
KeySpec publicKeySpec = new X509EncodedKeySpec(key);
KeyFactory kf = KeyFactory.getInstance("RSA");
Key pk = kf.generatePublic(publicKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
ByteArrayOutputStream out = new ByteArrayOutputStream();
CipherOutputStream cout = new CipherOutputStream(out, cipher);
try {
cout.write(plain.getBytes(UTF_8));
cout.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
cout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
encrypted = new String(encode(out.toByteArray(), DEFAULT), "UTF-8");
return encrypted;
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
static byte[] readFully(InputStream inputStream) throws IOException {
InputStream in = new BufferedInputStream(inputStream);
byte[] tmp = new byte[1024];
int readLen, size = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((readLen = in.read(tmp)) != -1) {
if (((long) size + readLen) > Integer.MAX_VALUE) {
// woah! did we just ship an app of 2GB?
throw new IllegalStateException("Invalid file. File size exceeds expected "
+ "maximum of 2GB");
}
size += readLen;
out.write(tmp, 0, readLen);
}
return out.toByteArray();
}
I have my key in encryption.der file. Everything works fine in android. Now coming to IOS which I'm using Ionic to develop. I'm not able to achieve the encryption part. I have used the "cryptico" : link : https://github.com/wwwtyro/cryptico/blob/master/README.md .
And finally converting to Base64 like these.
var EncryptionPassword = cryptico.encrypt($scope.userInfo.Password, publicKey);
$scope.encPass = base64.encode(EncryptionPassword.cipher);
But I'm getting ArrayIndexOutOfBound Exception from BL. Can you suggest exact same solution has android for angularjs too. So RSA encrytion works on both IOS and Android.
Create a Service and place your public Key inside that.
.service('Settings', function(){
this.publicKey = 'MIIBIjANBgdcssvsvsfvsfvsfvrefvfvfviuwoihijwfoiw278499080989i09M+KC8MYYOu/NRLmFg85LRrfRszyI/vZ/k8982789uiwbgchdbhU+3joQZoJ3Sxq/GbIIFf/3y4f9DuKI53y1qR2qD4xIskfa9rPVqvBtAu2KSNRd8V4J8RKI2gT2YEA+A3Z0mQq4GBRS8iYmGLqRQyPfNUSankylBrTpOIVFBZORdZehjJMmwl98UynyfnyMIHUIFuhefuibiufbeufbsoijn93fD7nxt+siZryfazn3EAgBaTKTV/U5xIepzDN6ZYJ4qnC93u6erdb1X4m1zU6RGapwzCOPOORTyzw/uWJ8twcODNt0cqVp+sYQIDAQAB';
})
Now in your JS encrypt using public key and JSEncrypt.
var encrypt = new JSEncrypt(); encrypt.setPublicKey(Settings.publicKey);
EncryptionPin = encrypt.encrypt($scope.customerInfo.Pin);
EncryptionPin is the final key.

How to implement PBE with MD5 and DES in Android to manipulate webview base URL?

How to implement PBEwithMD5andDES to encrypt the base url in webview? the following method I tried, but was unable to get any result. Again, I tried to make a separate class in eclipse and tried to pull the encrypted string to webview loadURL. There also, I was unable to add the output from the class as intent. How to do it, please help. the class is below (same examples I got in 3-4 places googling):
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class Helper {
public static Cipher dcipher, ecipher;
// Responsible for setting, initializing this object's encrypter and
// decrypter Chipher instances
Helper(String passPhrase) {
// 8-bytes Salt
byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03 };
// Iteration count
int iterationCount = 19;
try {
// Generate a temporary key. In practice, you would save this key
// Encrypting with DES Using a Pass Phrase
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt,
iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
.generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameters to the cipthers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidAlgorithmParameterException e) {
System.out.println("EXCEPTION: InvalidAlgorithmParameterException");
} catch (InvalidKeySpecException e) {
System.out.println("EXCEPTION: InvalidKeySpecException");
} catch (NoSuchPaddingException e) {
System.out.println("EXCEPTION: NoSuchPaddingException");
} catch (NoSuchAlgorithmException e) {
System.out.println("EXCEPTION: NoSuchAlgorithmException");
} catch (InvalidKeyException e) {
System.out.println("EXCEPTION: InvalidKeyException");
}
}
// Encrpt Password
#SuppressWarnings("unused")
protected String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
// Decrpt password
// To decrypt the encryted password
protected String decrypt(String str) {
Cipher dcipher = null;
try {
byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03 };
int iterationCount = 19;
try {
String passPhrase = "";
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(),
salt, iterationCount);
SecretKey key = SecretKeyFactory
.getInstance("PBEWithMD5AndDES")
.generateSecret(keySpec);
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameters to the cipthers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
iterationCount);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidAlgorithmParameterException e) {
System.out
.println("EXCEPTION: InvalidAlgorithmParameterException");
} catch (InvalidKeySpecException e) {
System.out.println("EXCEPTION: InvalidKeySpecException");
} catch (NoSuchPaddingException e) {
System.out.println("EXCEPTION: NoSuchPaddingException");
} catch (NoSuchAlgorithmException e) {
System.out.println("EXCEPTION: NoSuchAlgorithmException");
} catch (InvalidKeyException e) {
System.out.println("EXCEPTION: InvalidKeyException");
}
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
return null;
}
/**
* #param args
*/
public static void main(String[] args) {
try {
// Create encrypter/decrypter class
System.out.println("Inside Helper");
Helper encrypter = new Helper("");
// Pass the word to be Encrypted to Encrypt()
System.out.println("encrypt the String: SimplePassword");
String encrypted = encrypter.encrypt("SimplePassword");
System.out.println("encrypted String:" + encrypted);
// Pass the encrypted word to be Decrypted to Decrypt()
String decrypted = encrypter.decrypt(encrypted);
System.out.println("decrypted String:" + decrypted);
} catch (Exception e) {
}
}
}

Categories

Resources