With this way
I convert an image into a String.
Now I want to encrypt this string before send the data in server. Is there a simple way to encrypt and decrypt the string?
javax.crypto
This package provides the classes and interfaces for cryptographic applications implementing algorithms for encryption, decryption, or key agreement.
Stream ciphers are supported as well as asymmetric, symmetric and block ciphers. Cipher implementations from different providers can be integrated using the SPI (Service Provider Interface) abstract classes. With class SealedObject a programmer can secure an object by encrypting it with a cipher.
Authentication may be based on MAC (Message Authentication Code) such as HMAC (Hash MAC, i.e. with a SHA-1 hash function).
Example:
Simple helper class to encrypt and decrypt strings using AES128. The result is Ascii-encoded (actually hex, no base64), so no byte[] has to be stored. A SEED value is used as a shared secret ("Master-Password"). Only with the same SEED the stored values can be decrypted.
package com.xxx;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Usage:
* <pre>
* String crypto = SimpleCrypto.encrypt(masterpassword, cleartext)
* ...
* String cleartext = SimpleCrypto.decrypt(masterpassword, crypto)
* </pre>
* #author ferenc.hechler
*/
public class SimpleCrypto {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
For more info look at Android Security
How to encrypt and decrypt strings? and Encryption on Android & BouncyCastle
public class SecureCredentialsCrypto {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
//for storing encrypt it
String crypto_email = SecureCredentialsCrypto.encrypt("secure", email.toString().trim());
//for reading decrypt it
//crypto is object name to read
String correctEmail=SecureCredentialsCrypto.decrypt("secure", crypto);
package com.duplicate;
public class RSAEncryptionDescription {
private static final String PUBLIC_KEY_FILE = "Public.key";
private static final String PRIVATE_KEY_FILE = "Private.key";
public static void main(String[] args) throws IOException {
try {
System.out.println("-------GENRATE PUBLIC and PRIVATE KEY-------------");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); //1024 used for normal securities
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println("Public Key - " + publicKey);
System.out.println("Private Key - " + privateKey);
//Pullingout parameters which makes up Key
System.out.println("\n------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------\n");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
System.out.println("PubKey Modulus : " + rsaPubKeySpec.getModulus());
System.out.println("PubKey Exponent : " + rsaPubKeySpec.getPublicExponent());
System.out.println("PrivKey Modulus : " + rsaPrivKeySpec.getModulus());
System.out.println("PrivKey Exponent : " + rsaPrivKeySpec.getPrivateExponent());
//Share public key with other so they can encrypt data and decrypt thoses using private key(Don't share with Other)
System.out.println("\n--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------\n");
RSAEncryptionDescription rsaObj = new RSAEncryptionDescription();
rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());
//Encrypt Data using Public Key
byte[] encryptedData = rsaObj.encryptData("Anuj Patel - Classified Information !");
//Descypt Data using Private Key
rsaObj.decryptData(encryptedData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
/**
* Save Files
* #param fileName
* #param mod
* #param exp
* #throws IOException
*/
private void saveKeys(String fileName,BigInteger mod,BigInteger exp) throws IOException{
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
System.out.println("Generating "+fileName + "...");
fos = new FileOutputStream(fileName);
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(mod);
oos.writeObject(exp);
System.out.println(fileName + " generated successfully");
} catch (Exception e) {
e.printStackTrace();
}
finally{
if(oos != null){
oos.close();
if(fos != null){
fos.close();
}
}
}
}
/**
* Encrypt Data
* #param data
* #throws IOException
*/
private byte[] encryptData(String data) throws IOException {
System.out.println("\n----------------ENCRYPTION STARTED------------");
System.out.println("Data Before Encryption :" + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = null;
try {
PublicKey pubKey = readPublicKeyFromFile(PUBLIC_KEY_FILE);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encryptedData = cipher.doFinal(dataToEncrypt);
System.out.println("Encryted Data: " + encryptedData);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("----------------ENCRYPTION COMPLETED------------");
return encryptedData;
}
/**
* Encrypt Data
* #param data
* #throws IOException
*/
private void decryptData(byte[] data) throws IOException {
System.out.println("\n----------------DECRYPTION STARTED------------");
byte[] descryptedData = null;
try {
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
descryptedData = cipher.doFinal(data);
System.out.println("Decrypted Data: " + new String(descryptedData));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("----------------DECRYPTION COMPLETED------------");
}
/**
* read Public Key From File
* #param fileName
* #return PublicKey
* #throws IOException
*/
public PublicKey readPublicKeyFromFile(String fileName) throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
//Get Public Key
RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);
return publicKey;
} catch (Exception e) {
e.printStackTrace();
}
finally{
if(ois != null){
ois.close();
if(fis != null){
fis.close();
}
}
}
return null;
}
/**
* read Public Key From File
* #param fileName
* #return
* #throws IOException
*/
public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
//Get Private Key
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
} catch (Exception e) {
e.printStackTrace();
}
finally{
if(ois != null){
ois.close();
if(fis != null){
fis.close();
}
}
}
return null;
}
}
Related
I wanna encrypt the string with secret key and Iv. But i am not getting correct encryption. can any one tell me how to do this.
My string is abc but when decrypt the string it is contain special charaters in this.
i followed this link:
https://www.cuelogic.com/blog/using-cipher-to-implement-cryptography-in-android/
package com.reshhhjuuitos.mhhhkoiyrestos.footer;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MCrypt {
private String iv = "1234567890123456"; // Dummy iv (CHANGE IT!)
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "1&BZ6pqSu1w2%7!8w0oQHJ7FF79%+MO2";
public MCrypt() {
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
//cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception {
if (text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
// Cipher.ENCRYPT_MODE = Constant for encryption operation mode.
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(padString(text).getBytes("UTF-8"));
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
private static String padString(String source) {
char paddingChar = 0;
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
return source;
}
public static byte[] hexToBytes(String str) {
if (str == null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(
str.substring(i * 2, i * 2 + 2), 16);
}
return buffer;
}
}
public static String byteArrayToHexString(byte[] array) {
StringBuffer hexString = new StringBuffer();
for (byte b : array) {
int intVal = b & 0xff;
if (intVal < 0x10)
hexString.append("0");
hexString.append(Integer.toHexString(intVal));
}
return hexString.toString();
}
public byte[] decrypt(String text) throws Exception {
if (text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
// Cipher.DECRYPT_MODE = Constant for decryption operation mode.
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(text));
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
}
MainACTVITIY.JAVA
MCrypt mycrypt = new MCrypt();
String dummyStr = "abc";
try {
String encryptedStr = mycrypt.byteArrayToHexString(mycrypt.encrypt(dummyStr));
String decryptedStr = new String(mycrypt.decrypt(encryptedStr));
Log.v("Tag_en",""+encryptedStr);
Log.v("Tag_de",""+decryptedStr);
} catch (Exception e) {
e.printStackTrace();
}
output:Tag_en:5b49ac218b93ee5315c25a0e40b3e9de42e6ecadf0827062b22d4421da99dc5a
Tag_de: abc��������������������������
Okay, I thought it might be your hex encode/decode, but they work. So I wrote some quick encryption and tested it against your class.
The problem is your padding. I don't understand why you are padding your string to length 16, but it is the null characters you have appended to your string that are unprintable. So either don't pad the string, or strip the padding nulls during decryption to rebuild the exact string you encrypted.
For clarity, maintainability and re-usability, you should really do just one clear logical operation in each of your methods, i.e. padding should be done before you pass the string to the encryption method, so the encryption method just encrypts.
You could use functions like these:
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
And invoke them like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();
byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
// encrypt
byte[] encryptedData = encrypt(key,b);
// decrypt
byte[] decryptedData = decrypt(key,encryptedData);
This should work, I use similar code in a project right now.
I am using Volley to send data to my server and I am putting all the necessary data in the header and in the body of the stringRequest.
After I send the request, I can capture the packages using WireShark and I am able to see all the data that has been sent, from the token in the header to all of the fields in the body (userId, etc).
How is encryption used in network connections using Volley?
Is it any way to encrypt the data in the header and the body of the request?
you can use AES algorithm
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryptionDecryption {
private static final byte[] keyValue =
new byte[]{'c', 'o', 'd', 'i', 'n', 'g', 'a', 'f', 'f', 'a', 'i', 'r', 's', 'c', 'o', 'm'};
public static String encrypt(String cleartext)
throws Exception {
byte[] rawKey = getRawKey();
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String encrypted)
throws Exception {
byte[] enc = toByte(encrypted);
byte[] result = decrypt(enc);
return new String(result);
}
private static byte[] getRawKey() throws Exception {
SecretKey key = new SecretKeySpec(keyValue, "AES");
byte[] raw = key.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKey skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] encrypted)
throws Exception {
SecretKey skeySpec = new SecretKeySpec(keyValue, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
for encryption use this method
String encrypted = "";
try {
encrypted = AESEncryptionDecryption.encrypt(plain_text);
Log.d(Constants.firebase_app, "encrypted:" + encrypted);
} catch (Exception e) {
e.printStackTrace();
}
for decryption use this method
String decrypted = "";
try {
decrypted = AESEncryptionDecryption.decrypt(encrypted);
Log.d(Constants.firebase_app, "decrypted:" + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
How to encrypt and decrypt a string in android using AES with Salt+password+iv . I want code equivalent to https://stackoverflow.com/a/27893935/5582162. This link has working code for node.js and iOS but I want same/equivalent code in android format.
Using the above link --
Eg:
RawData: pravin
password: sbifast12
salt: gettingsaltyfoo!
iv: QmBSbUZMUwld31DPrqyVSA==
Encrypted Key should be: AbvDUXUG9p1ysz1a1ZANSA==
Code that I tried:
try {
// byte[] salt = generateSalt();
byte[] salt = saltStr.getBytes();
// Log.i(TAG, "Salt: " + salt.length + " " + HexEncoder.toHex(salt));
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT, 128);
SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGORITHM);
SecretKey tmp = factory.generateSecret(pbeKeySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
byte[] key = secret.getEncoded();
//Log.i(TAG, "Key: " + HexEncoder.toHex(key));
// PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATION_COUNT);
Cipher encryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM);
// byte[] encryptionSalt = generateSalt();
// Log.i(TAG, "Encrypted Salt: " + encryptionSalt.length + " " + HexEncoder.toHex(encryptionSalt));
// PBEParameterSpec pbeParamSpec = new PBEParameterSpec(encryptionSalt, 1000);
// byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
Log.i(TAG, encryptionCipher.getParameters() + " ");
// byte[] iv = generateIv();
//byte[] iv ="QmBSbUZMUwld31DPrqyVSA==".getBytes();
IvParameterSpec ivspec = new IvParameterSpec(Arrays.copyOf(iv,16));
encryptionCipher.init(Cipher.ENCRYPT_MODE, secret, ivspec);
byte[] encryptedText = encryptionCipher.doFinal(plainText.getBytes());
// Log.i(TAG, "Encrypted: " + new String(encryptedText));
Log.i(TAG, "Encrypted: " + Base64.encodeToString(encryptedText, Base64.DEFAULT));
Cipher decryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM);
decryptionCipher.init(Cipher.DECRYPT_MODE, secret, ivspec);
byte[] decryptedText = decryptionCipher.doFinal(encryptedText);
Log.i(TAG, "Decrypted....: " + new String(decryptedText));
} catch (Exception e) {
e.printStackTrace();
}
And also...
public class AesEncryption2 {
private static String password = "sbifast12";
/**
* vector array for encryption & decryption
*/
private static byte[] iv = "QmBSbUZMUwld31DPrqyVSA==".getBytes();
private static String IV = "QmBSbUZMUwld31DPrqyVSA==";
private static String salt = "gettingsaltyfoo!";
private static String CIPHERTEXT = "CIPHERTEXT!";
public static void main(String rawData) {
byte[] interop_iv = Base64.decode(IV, Base64.DEFAULT);
// byte[] iv = null;
byte[] ciphertext;
SecretKeySpec secret=null;
try {
secret = generateKey(password.toCharArray(), salt.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Map result = null;
try {
result = encrypt(rawData, iv, secret);
} catch (Exception e) {
e.printStackTrace();
}
ciphertext = (byte[]) result.get(CIPHERTEXT);
iv = (byte[]) result.get(IV);
System.out.println("Cipher text:" + Base64.encode(ciphertext, Base64.DEFAULT));
System.out.println("IV:" + Base64.encode(iv, Base64.DEFAULT) + " (" + iv.length + "bytes)");
System.out.println("Key:" + Base64.encode(secret.getEncoded(), Base64.DEFAULT));
try {
System.out.println("Deciphered: " + decrypt(ciphertext, iv, secret));
} catch (Exception e) {
e.printStackTrace();
}
// Interop demonstration. Using a fixed IV that is used in the C#
// example
try {
result = encrypt(rawData, interop_iv, secret);
} catch (Exception e) {
e.printStackTrace();
}
ciphertext = (byte[]) result.get(CIPHERTEXT);
iv = (byte[]) result.get(IV);
String text = Base64.encodeToString(ciphertext, Base64.DEFAULT);
System.out.println();
System.out.println("--------------------------------");
System.out.println("Interop test - using a static IV");
System.out.println("The data below should be used to retrieve the secret message by the receiver");
System.out.println("Cipher text: " + text);
System.out.println("IV: " + Base64.encodeToString(iv, Base64.DEFAULT));
try {
decrypt(Base64.decode(text, Base64.DEFAULT), iv, secret);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SecretKeySpec generateKey(char[] password, byte[] salt) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 1024, 128);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(tmp.getEncoded(), "AES");
return secret;
}
public static Map encrypt(String cleartext, byte[] iv, SecretKeySpec secret) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// If the IvParameterSpec argument is omitted (null), a new IV will be
// created
cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
AlgorithmParameters params = cipher.getParameters();
byte[] usediv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(cleartext.getBytes("UTF-8"));
Map result = new HashMap();
result.put(IV, usediv);
result.put(CIPHERTEXT, ciphertext);
return result;
}
public static String decrypt(byte[] ciphertext, byte[] iv, SecretKeySpec secret) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8");
return plaintext;
}
Third method:
private static final String ALGO = "AES";
/**
* key value for encryption & decryption
*/
private static String password = "sbifast12";
private static byte[] iv = "QmBSbUZMUwld31DPrqyVSA==".getBytes();
private static String IV = "QmBSbUZMUwld31DPrqyVSA==";
private static String salt = "gettingsaltyfoo!";
/**
* constructor with two variable parameters
* #param password
* #param iv
*/
/* public AESEncryption(String password, String iv) {
if (password == null || iv == null)
throw new NullPointerException("Encryption values can not be null!");
this.password = password.getBytes();
this.iv = iv.getBytes();
}*/
/**
* encrypt given string data
*
* #param rawdata
* #return
* #throws Exception
*/
public static String encrypt(String rawdata) throws Exception {
if (rawdata == null)
throw new NullPointerException("Raw data can not be null!");
//SecretKeySpec sKey = (SecretKeySpec) generateKeyFromPassword(password, saltBytes);
//SecretKey key = new SecretKeySpec(Base64.decode(salt,Base64.DEFAULT), "AES");
// Key key = generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
/* cipher.init(Cipher.ENCRYPT_MODE, generateKeyFromPassword("sbifast12", salt.getBytes()),
new IvParameterSpec(Arrays.copyOf(IV.getBytes("UTF-8"), 16)));
*/
cipher.init(Cipher.ENCRYPT_MODE, generateKeyFromPassword("sbifast12", salt.getBytes()),
new IvParameterSpec(Arrays.copyOf(IV.getBytes(),16)));
byte[] encVal = cipher.doFinal(rawdata.getBytes());
String encryptedValue = Base64.encodeToString(encVal, Base64.DEFAULT);
System.out.println("%%%%%%% Encrypted Text: " + encryptedValue);
return encryptedValue;
}
public static SecretKey generateKeyFromPassword(String password, byte[] saltBytes) throws GeneralSecurityException {
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes, 1000, 128);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithSHA256AND256BITAES");
SecretKey secretKey = keyFactory.generateSecret(keySpec);
return new SecretKeySpec(secretKey.getEncoded(), "AES");
}
/**
* decrypt given string data
*
* #param encryptedData
* #return
* #throws Exception
*/
public String decrypt(String encryptedData) throws Exception {
if (encryptedData == null)
throw new NullPointerException("Encrypted data can not be null!");
Key key = generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] decodedValue = Base64.decode(encryptedData, Base64.DEFAULT);
byte[] decValue = cipher.doFinal(decodedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
/**
* key generator
*
* #return
* #throws Exception
*/
private Key generateKey() throws Exception {
Key key = new SecretKeySpec("sbifast12".getBytes(), ALGO);
return key;
}
public class Cryptography {
private static final String TAG = "Cryptography";
//secretKey64 is genereated from salt and password..!!! (taken directly from server side)
private static String secretKey64 = "*****1hrHpnONd8ZJ*****c756ikDmZU1v*****8Xjg=";
private static String secretKeyAlgorithm = "AES";
private static String cipherAlgorithm = "AES/CBC/PKCS7Padding";
private static String iv64 = "QmBSbU*****d31DPr*****==";
private static String charsetName = "UTF-8";
// private static int base64Mode = android.util.Base64.DEFAULT;
private static int base64Mode = android.util.Base64.NO_WRAP;
public static String encrypt(String plainText) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException
, IllegalBlockSizeException, BadPaddingException {
String encrytedText = "";
if (plainText == null) {
return null;
} else {
SecretKey secretKey = new SecretKeySpec(android.util.Base64.decode(secretKey64, 0), secretKeyAlgorithm);
IvParameterSpec iv = new IvParameterSpec(android.util.Base64.decode(iv64, 0));
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] dataBytes = plainText.getBytes(charsetName);
encrytedText = Base64.encodeToString(cipher.doFinal(dataBytes), base64Mode);
}
// Log.d(TAG, "ENCRYPT >>>> : " + encrytedText);
return encrytedText;
}
public static String decrypt(String encryptedText) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException
, IllegalBlockSizeException, BadPaddingException, NullPointerException {
String plainText = "";
SecretKey secretKey = new SecretKeySpec(android.util.Base64.decode(secretKey64, 0), secretKeyAlgorithm);
IvParameterSpec iv = new IvParameterSpec(android.util.Base64.decode(iv64, 0));
byte[] dataBytesD = Base64.decode(encryptedText, base64Mode);
Cipher cipherD = Cipher.getInstance(cipherAlgorithm);
cipherD.init(2, secretKey, iv);
//Log.d(TAG, "DECRYPT text:- >>>> : " + encryptedText);
byte[] dataBytesDecrypted = cipherD.doFinal(dataBytesD);
try {
plainText = new String(dataBytesDecrypted);
} catch (NullPointerException e) {
e.printStackTrace();
}
//Log.d(TAG, "DECRYPT >>>> : " + plainText);
return plainText;
}
}
I want to encode and decode a File in Android but when i try to decrypt some File it returns an empty array of bytes.
The class I use to encrypt the File and decrypt:
public class CrytedClass {
public static byte[] generateKey(String pass) throws Exception{
byte [] start = pass.getBytes("UTF-8");
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(start);
kgen.init(128,sr);
SecretKey skey = kgen.generateKey();
return skey.getEncoded();
}
public static byte[] encodedFile(byte[] key, byte[] fileData)throws Exception{
SecretKeySpec skeySpec = new SecretKeySpec(key,"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte [] encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception{
SecretKeySpec skeySpec = new SecretKeySpec(key,"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);
byte [] decrypted = cipher.doFinal(fileData);
return decrypted;
}
public static String generatePass(){
return new BigInteger(130, new SecureRandom()).toString(32);
}
public static byte[] createHas(byte[] ficheroEncrip){
MessageDigest msd = null;
try{
msd = MessageDigest.getInstance("SHA-1");
}catch (Exception e){
return null;
}
msd.update(ficheroEncrip);
return msd.digest();
}
}
The test code i use.
try {
String id1 = CrytedClass.generatePass();
byte[] secure = CrytedClass.generateKey(id1);
byte[] FileEncoded = CrytedClass.encodedFile(secure, ous.toByteArray());
byte[] decoded = CrytedClass.decodeFile(secure, FileEncoded);
File decodedFile = new File(Environment.getExternalStorageDirectory()+"/decoded.pdf");
FileOutputStream pdfFile = new FileOutputStream(decodedFile);
pdfFile.write(decoded);
System.out.println("Final del test");
Boolean r = pdfFile.equals(original);
}catch(Exception e){
}
Thanks for your help
I recently purchased and HTC One and test ran some code on it that is working fine on my old Moto Razr. I am getting a BadPaddingException, pad block corrupted. Encryption is needed just to hide a pass phrase in the preferences.. it's not critical. I'm just trying to obscure it a little. Here is the exception and below is the Class that I found on a forum. Encryption is my weak point. I am just not advanced enough yet to really grasp what is going on. Any help would be greatly appreciated.
10-28 15:51:26.754: W/System.err(30090): javax.crypto.BadPaddingException: pad block corrupted
10-28 15:51:26.764: W/System.err(30090): at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:709)
10-28 15:51:26.764: W/System.err(30090): at javax.crypto.Cipher.doFinal(Cipher.java:1111)
10-28 15:51:26.764: W/System.err(30090): at com.seine.trophy.main.SimpleCrypto.decrypt(SimpleCrypto.java:63)
10-28 15:51:26.764: W/System.err(30090): at com.seine.trophy.main.SimpleCrypto.decrypt(SimpleCrypto.java:36)
Java source code:
/**
* Usage:
*
* <pre>
* String crypto = SimpleCrypto.encrypt(masterpassword, cleartext)
* ...
* String cleartext = SimpleCrypto.decrypt(masterpassword, crypto)
* </pre>
*
* #author ferenc.hechler
*/
public class SimpleCrypto {
private final static String HEX = "0123456789ABCDEF";
public static String encrypt(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
Thanks for any help!