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.
Asked
Active
Viewed 8,940 times
1
-
i dont know about encrypt and decrypt . pls help me @Pheonix – Vigneshwaran T Oct 31 '17 at 05:17
-
Google it up, check out existing examples. at least try out codes from 3 different results. – Pheonix Oct 31 '17 at 05:29
2 Answers
7
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 + "\"");
}

jafarbtech
- 6,842
- 1
- 36
- 55
-
DES has been broken for years. Please don't recommend the use of DES in future projects, even if they are just for personal use. The code above also uses ECB mode, which is insecure. – Luke Joshua Park Oct 31 '17 at 06:35
-
@LukePark But there is no public announcement [here](https://developer.android.com/reference/javax/crypto/spec/DESKeySpec.html) – jafarbtech Oct 31 '17 at 06:38
-
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder(); sun.misc.BASE64Decoder base64decoder = new BASE64Decoder(); it shows cannot resolve symbol – Vigneshwaran T Oct 31 '17 at 06:39
-
That is for legacy support. DES has been broken for a very long time and is not secure for use. Please amend your code example or remove it, recommending the use of DES is very poor practice. See here https://stackoverflow.com/questions/1619212/is-des-or-3des-still-being-used-today – Luke Joshua Park Oct 31 '17 at 06:40
-
1
-
1. generateKey returns `SecretKey` not `String` 2. Note that `mySecret` has to have e.g.16 bytes to work! Yours has 17 and therefore throws an exception: `java.security.InvalidKeyException: Unsupported key size: 17 bytes` – derHugo Jun 04 '18 at 11:01
0
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
}

Piyal Maduranga
- 48
- 5
-
i dint have any idea about your answer i cant understand ? @Piyal Maduraga – Vigneshwaran T Oct 31 '17 at 05:54
-
this is encryption and decryption mechanism using one time key , that mean same key use for encryption and decryption – Piyal Maduranga Oct 31 '17 at 06:18
-
ok where is the function static BASE64Encoder enc = new BASE64Encoder(); ? @Piyal Maduranga – Vigneshwaran T Oct 31 '17 at 06:26
-
Using XOR as an "encryption algorithm" for any reason other than to experiment is a bad idea, regardless of security requirements. Please don't recommend this. – Luke Joshua Park Oct 31 '17 at 06:35
-
The text of this answer isn't describing a one-time pad. To be a one-time pad, the key must be used, well, one time. If two different messages can be combined to produce useful information, the key was used more than one time. Furthermore, [XORing the codetexts](https://crypto.stackexchange.com/q/59/56919) doesn't produce the key but rather removes the key (`(A ⊕ K) ⊕ (B ⊕ K) = A ⊕ B`). – outis Mar 13 '18 at 17:09