Android Studio cannot decrypt message in AES - java

hi, i try to implement aes in some open source code messaging application. for encrypted message, its work find to me. but i have difficulty to decrypt back message.
in this class, i can encrypted message and it work fine.
MessageActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
messageView = (TextView) findViewById(R.id.message_view);
final Button button = (Button) findViewById(R.id.btn_send);
final EditText message = (EditText) findViewById(R.id.edit_message);
this.setTitle("Group Chat");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = message.getText().toString();
byte[] cipherText = null;
try {
cipherText = AESEncryption.encryptText(str, AESEncryption.thisKey());
} catch (Exception e) {
e.printStackTrace();
}
String msgStr = new String(cipherText);
addMessage("This phone", str);
message.setText("");
// Send to other clients as a group chat message
for (AllEncompasingP2PClient c : MeshNetworkManager.routingTable.values()) {
if (c.getMac().equals(MeshNetworkManager.getSelf().getMac()))
continue;
Sender.queuePacket(new Packet(Packet.TYPE.MESSAGE, msgStr.getBytes(), c.getMac(),
WiFiDirectBroadcastReceiver.MAC));
}
}
});
Receiver.java
/////////////// this messsage receiver part///////////////////////
byte[] thisMsg = p.getData();
String decryptedText = null;
try {
decryptedText = AESEncryption.decryptText(thisMsg, AESEncryption.thisKey());
} catch (Exception e) {
e.printStackTrace();
}
final String message = p.getSenderMac() + " says:\n" + decryptedText;
final String msg = new String(p.getData());
final String name = p.getSenderMac();
//////////////////////////////////////
if (!MeshNetworkManager.routingTable.contains(p.getSenderMac())) {
/*
* Update your routing table if for some reason this
* guy isn't in it
*/
MeshNetworkManager.routingTable.put(p.getSenderMac(),
new AllEncompasingP2PClient(p.getSenderMac(), p.getSenderIP(),
p.getSenderMac(),
MeshNetworkManager.getSelf().getGroupOwnerMac()));
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (activity.isVisible) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
} else {
MessageActivity.addMessage(name, msg);
}
}
});
updatePeerList();
AESEncryption.java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
//import javax.xml.bind.DatatypeConverter;
public class AESEncryption {
public static SecretKey getSecretEncryptionKey() throws Exception{
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128); // The AES key size in number of bits
SecretKey secKey = generator.generateKey();
return secKey;
}
public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
return byteCipherText;
}
public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
return new String(bytePlainText);
}
public static SecretKey thisKey() throws Exception{
SecretKey secKey = AESEncryption.getSecretEncryptionKey();
return secKey;
}
}
in this class where i code the decrypted message. but when i run the code, the messages not decrypt and show ciphert text instead.if someone can correct me, its will great.

The same key must be used for both encryption and decryption for the same message.
It seems the same key is not being used for both encryption and decryption, both methods call SecretKey thisKey() which seems to generate a random key.
On encryption call SecretKey thisKey(), use it for encryption and save the key to use on decryption. On decryption do not call SecretKey thisKey(), use the key created for encryption.

Related

Encrypt a field to send to another API

I have a request where there is a field "number_token" that I need to encrypt to send to another API to validate. What is the best method to do this?
Example:
"number_token":"123456789"
encrypt:
"number_token":"iIsInN1YieyJpc3MiOiJHZXR3YXk.gcGFnQmFuayBQQI6ImIyYzMxMTlmLWU3ZjktNDZjZS05NTMxLTkyMTNlNWRjNWNiMSIsImlhdCI6MTY1OTgyNjUyOCwiZXhwIjoxNjU5ODI2NzA4fQ.mL-jivitV30N1PLq10CmI4ZWxCcBivGf5QGVus7Vsyw"
There are many factors to be considered but to get started you can use below logic to encrypt. Credits https://www.javaguides.net/2020/02/java-string-encryption-decryption-example.html?m=1
Here is the complete Java program to encrypt and decrypt string or text in Java:
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryptionDecryption {
private static SecretKeySpec secretKey;
private static byte[] key;
private static final String ALGORITHM = "AES";
public void prepareSecreteKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes(StandardCharsets.UTF_8);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public String encrypt(String strToEncrypt, String secret) {
try {
prepareSecreteKey(secret);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public String decrypt(String strToDecrypt, String secret) {
try {
prepareSecreteKey(secret);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void main(String[] args) {
final String secretKey = "secrete";
String originalString = "javaguides";
AESEncryptionDecryption aesEncryptionDecryption = new AESEncryptionDecryption();
String encryptedString = aesEncryptionDecryption.encrypt(originalString, secretKey);
String decryptedString = aesEncryptionDecryption.decrypt(encryptedString, secretKey);
System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}

how to encrypt/decrypt text in android studio on different activities

I tried developing an text encryption/decryption app in android studio. So here on the MainActivity.java i ran a sample code of encryption & decryption.
MainActivity.java
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends AppCompatActivity {
Button btn,btn2;
static final String TAG = "SymmetricAlgorithmAES";
String secr="k";
String secr2="d";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code to use my specified defined key
byte[] key = new byte[0];
try {
key = (secr+secr2).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec sks = new SecretKeySpec(key, "AES");
// Original text
String theTestText = "This is just a simple test";
TextView tvorig = (TextView)findViewById(R.id.tvorig);
tvorig.setText("\n[ORIGINAL]:\n" + theTestText + "\n");
// Encode the original data with AES
byte[] encodedBytes = null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, sks);
encodedBytes = c.doFinal(theTestText.getBytes());
} catch (Exception e) {
Log.e(TAG, "AES encryption error");
}
TextView tvencoded = (TextView)findViewById(R.id.tvencoded);
tvencoded.setText("" +
Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");
// Decode the encoded data with AES
byte[] decodedBytes = null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, sks);
decodedBytes = c.doFinal(encodedBytes);
} catch (Exception e) {
Log.e(TAG, "AES decryption error");
}
TextView tvdecoded = (TextView)findViewById(R.id.tvdecoded);
tvdecoded.setText("[DECODED]:\n" + new String(decodedBytes) + "\n");
}
The above code works properly with correct output. But when i try to modify the code and try to write encryption and decryption in different activities, but the decryption part does not work properly.
Here is the code for encryption part which works properly without any error.
Encryption.java
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Encryption extends AppCompatActivity {
static final String TAG = "SymmetricAlgorithmAES";
String secr="k";
String secr2="d";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.encryption);
enc_text_edt=(EditText)findViewById(R.id.enc_text_edt);
enc_text_btn=(Button)findViewById(R.id.enc_text_btn);
enctv=(TextView)findViewById(R.id.enctv);
//code to use my specified defined key
byte[] key = new byte[0];
try {
key = (secr+secr2).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec sks = new SecretKeySpec(key, "AES");
final SecretKeySpec finalSks = sks;
enc_text_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
// Encode the original data with AES
byte[] encodedBytes = null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, finalSks);
encodedBytes = c.doFinal(enc_text_edt.getText().toString().getBytes());
} catch (Exception e) {
Log.e(TAG, "AES encryption error");
}
enctv.setText("[ENCRYPTED]:\n" +
Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");
enc_text_edt.setText("");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
code of Decryption
Decryption.java
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Decryption extends AppCompatActivity {
Button dec_text_btn;
TextView dec_edtext_view, dectv;
static final String TAG = "SymmetricAlgorithmAES";
String secr = "k";
String secr2 = "d";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.decryption);
dec_text_btn = (Button) findViewById(R.id.dec_text_btn);
dec_edtext_view = (EditText) findViewById(R.id.dec_edtext_view);
dectv = (TextView) findViewById(R.id.dectv);
//code to use my specified defined key
byte[] key = new byte[0];
try {
key = (secr + secr2).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec sks = new SecretKeySpec(key, "AES");
final SecretKeySpec finalSks = sks;
dec_text_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
// Decode the encoded data with AES
byte[] decodedBytes = null;
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, finalSks);
decodedBytes= c.doFinal(dec_edtext_view.getText().toString().getBytes());
} catch (Exception e) {
Log.e(TAG, "AES encryption error");
}
dectv.setText("[DECRYPTED]:\n" + new String(decodedBytes) + "\n");
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "creptography exception see log cat....", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Please help me with the error. While executing Decryption part it directly shows exception "creptography exception see log cat".
After reading your code I think I have found the problem, you encode to Base64 but never decode. In the Encryption you do the following
enctv.setText("[ENCRYPTED]:\n" +
Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");
and I can guess the user copies it to the decryption field but after they click the button you do
decodedBytes= c.doFinal(dec_edtext_view.getText().toString().getBytes());
instead of decoding from Base64.
I would also like to add a few notes:
You're security is not safe, you barely achieved any layer of security when the keys are in plane site like this.
Note 1:
Keys should be generated randomly with a SecureRandom.
You can easily do it by doing the following:
byte[] key = new byte[16];
new SecureRandom().nextBytes(key);
Note 2:
Use an initialization vector aka IV this is useful in case the user has typed the same message. For example consider the following scenario you encrypt "Hello World" and it comes out as "ABCDEFGHIJK". Now you send it again and it is again "ABCDEFGHIJK".
With an IV it will be different everytime as long as you generate a new IV per message, you should append this IV to the message so later in decryption you can extract it.
Note 3:
When declaring a Cipher use more than AES.
There is a great article about how to increase your security and knowledge: article link
Note 4:
If an exception occurs don't continue on like nothing happend, you should handle it correctly and not continue on code that depends on what caused the exception.
Note 5:
Learn Java more in depth instead of jumping to cryptography, you're fields should be private and some final don't declare null if you might be planning to use it later, if you do check if its null. Don't declare "UTF-8" in get bytes, have a constant declaring a Charset such as "UTF-8" this is easily done with Charset.forName("UTF-8")
I agree with everything OughtToPrevail said.
Also, you should probably get all of that out of your activity and into a helper class. That way it will be reusable, and you can test the in and out of it (without copying and pasting) with something that would look like this:
public void myEncryptionTest(){
String message = "This is the message to encrypt and decrypt.";
String pass = "pass";
String encryption = Crypto.myEncrypt(message.getBytes(), pass);
byte[] decryption = Crypto.myDecrypt(encryption, pass);
String decrypted = new String(decryption);
Log.d("****DECRYPTION: ", decrypted);
}
Where the helper class is called "Crypto" and the two static functions you're testing are "myEncrypt" and "myDecrypt."

Android AES decryption returning rare characters

I'm trying to decrypt a String text with the AES algorithm and I found many tutorials but still getting the same error when I try to decrypt the String.
Here is my class:
EditText inputText, inputPass;
TextView out;
Button btnEnc, btnDec;
String outputString;
private static final String AES_MODE = "AES";
View.OnClickListener encryption= new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
outputString= encrypt(inputText.getText().toString(),inputPass.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
out.setText(outputString);
}
};
View.OnClickListener decryption= new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
outputString= decrypt(outputString,inputPass.getText().toString());
} catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
e.printStackTrace();
}
out.setText(outputString);
}
};
private String encrypt(String data, String pass)throws Exception{
SecretKeySpec key= generateKey(pass);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.ENCRYPT_MODE,key);
byte[] encVal= c.doFinal(data.getBytes());
String encryptedValue= Base64.encodeToString(encVal,Base64.DEFAULT);
return encryptedValue;
}
private String decrypt(String cadena, String password)throws Exception{
SecretKeySpec keySpec= generateKey(password);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decValue= Base64.decode(cadena, Base64.DEFAULT);
String decryptedValue= new String((decValue));
return decryptedValue;
}
private SecretKeySpec generateKey(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest= MessageDigest.getInstance("SHA-256");
byte[] bytes= password.getBytes("UTF-8");
digest.update(bytes,0,bytes.length);
byte[] key= digest.digest();
SecretKeySpec secretKeySpec= new SecretKeySpec(key, "AES");
return secretKeySpec;
}
The problem is when I try to retrieve the Decrypted string because it returns this:
As you can see, the output text contains Unicode characters and not the text that I've encrypted. What would be the problem?
You forgot to actually call your cipher in the decrypt method.
private String decrypt(String cadena, String password)throws Exception{
SecretKeySpec keySpec= generateKey(password);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decValue= c.doFinal(Base64.decode(cadena, Base64.DEFAULT));
// ^^^^^^^^^ add this
String decryptedValue= new String((decValue));
return decryptedValue;
}
Furthermore, you should always explicitly specify an encoding when converting from a byte[] to a String or vice versa.

Decrypting returns, javax.crypto.BadPaddingException: Given final block not properly padded

Im trying to decrypt the encrypted xml file. Im getting it as a inputstream as follows.I have the correct encrypt key. but each time my program returns empty string. Every time i enter the correct key. but each time it returns Badpadding Exception.
try{
InputStream is = new ByteArrayInputStream(decryption.getFileData().getBytes());
String xmlEncryptedStr = getStringFromInputStream(is);
String xmlStr = CipherUtils.decrypt(xmlEncryptedStr, new Long(key));
.......
here is my CipherUtils.java class
.........
public static String decrypt(String strToDecrypt,Long key)
{
String keyString=String.format("%016d", key);
//System.out.println("decrypt keyString :"+keyString);
return decrypt(strToDecrypt, keyString.getBytes());
}
public static String decrypt(String strToDecrypt,byte[] key)
{
if(strToDecrypt==null)
return strToDecrypt;
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
System.out.println("CipherUtils.decryptedString :"+decryptedString);
return decryptedString;
}
catch (Exception e)
{
log.error("Ops!", e);
}
return null;
}
.......
For more information here is my encrypting code
public static String encrypt(String strToEncrypt,Long key)
{
String keyString=String.format("%016d", key);
//System.out.println("encrypt keyString :"+keyString);
return encrypt(strToEncrypt,keyString.getBytes());
}
public static String encrypt(String strToEncrypt,byte[] key)
{
if(strToEncrypt==null)
return strToEncrypt;
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
final String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
// System.out.println("CipherUtils.encrypt :"+encryptedString);
return encryptedString;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
I am sorry I couldn't comment so I am writing in answers section.
I faced this issue when I was using different keys though I was passing the same but i used CBC methodology.
Just to note that have you checked that encryption is also done by the AES/ECB/PKCS5Padding and not other format like AES/CBC/PKCS5Padding
Also check if key format for encryption is also having the same format like %016d of your keyValue. Also the key is 16 char long.
I created a simple AES and DESede encryption utility and it worked fine.
private static final byte[] keyValue = new String(
"CjxI&S#V&#DSA_S0dA-SDSA$").getBytes();
public static void main(String[] args) throws Exception {
Client cli = new Client();
System.out.println(cli.encrypt("your password for encryption"));
Client cli1 = new Client();
System.out.println(cli1.decrypt("fTsgVQtXvv49GynHazT4OGZ4Va1H57d+6AM+44Ex040="));
}
public String encrypt(String Data) throws Exception {
Key key = new SecretKeySpec(keyValue, "AES");
Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = DatatypeConverter.printBase64Binary(encVal);
// String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public String decrypt(String encryptedData) throws Exception {
Key key = new SecretKeySpec(keyValue, "AES");
Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = DatatypeConverter
.parseBase64Binary(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}

How to use 3DES algorithm on Android?

On the server side, the encyption/decryption of the password field is done in C#.
Now, i need to implement same functionality in my android application. So, i followed this tutorial: http://ttux.net/post/3des-java-encrypter-des-java-encryption/ as below:
import java.security.MessageDigest;
import java.security.spec.KeySpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Base64;
public class Encrypter {
private KeySpec keySpec;
private SecretKey key;
private IvParameterSpec iv;
public Encrypter(String keyString, String ivString) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("utf-8")));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
keySpec = new DESedeKeySpec(keyBytes);
key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
iv = new IvParameterSpec(ivString.getBytes());
} catch(Exception e) {
e.printStackTrace();
}
}
public String encrypt(String value) {
try {
Cipher ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding","SunJCE");
ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
if(value==null)
return null;
// Encode the string into bytes using utf-8
byte[] utf8 = value.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new String(Base64.encodeBase64(enc),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String decrypt(String value) {
try {
Cipher dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding","SunJCE");
dcipher.init(Cipher.DECRYPT_MODE, key, iv);
if(value==null)
return null;
// Decode base64 to get bytes
byte[] dec = Base64.decodeBase64(value.getBytes());
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
but i dont know what values i need to provide for KeyValue and ivValue for the above code. Please help me...
Use this code to encrypt your string
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
//string encryption
public class EncryptionHelper {
// Encrypts string and encode in Base64
public static String encryptText(String plainText) throws Exception {
// ---- Use specified 3DES key and IV from other source --------------
byte[] plaintext = plainText.getBytes();//input
byte[] tdesKeyData = Constants.getKey().getBytes();// your encryption key
byte[] myIV = Constants.getInitializationVector().getBytes();// initialization vector
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(myIV);
c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(plaintext);
String encryptedString = Base64.encodeToString(cipherText,
Base64.DEFAULT);
// return Base64Coder.encodeString(new String(cipherText));
return encryptedString;
}
}
This is how you can encrypt the string
String encryptedPassword = EncryptionHelper.encryptText(edtText.getText().toString());
EDIT
Code for Constants.java
Class Constants {
private final String initializationVector = "INITALIZATION_VECTOR";
private final String ecnryptionKey = "ENCRYPTION_KEY";
public static String getInitializationVector() {
return initializationVector;
}
public static String getKey() {
return ecnryptionKey;
}
}
Triple DES is called "DESede" (DES using single DES Encrypt, Decrypt, Encrypt for encryption) in both Java and Android runtimes. So it is build in functionality which can be access through the Cipher class. It also lists the available algorithms. For triple DES you could use "DESede/CBC/PKCS5Padding"`. Don't forget to supply it a random IV of 8 bytes.
Triple DES should only be used for backwards compatibility. If you decide to use it at least supply it 24 bytes of key material, otherwise there is a chance that your ciphertext can be cracked. For a more modern approach use AES, preferably in an authenticated mode such as GCM ("AES/GCM/NoPadding"). Note that GCM requires a unique nonce of 12 bytes.

Categories

Resources