javax.crypto funciona de forma diferente em diferentes viewsões do operating system Android?

Estou usando este fragment de código paira criptografair / descriptografair dados no database do meu aplicativo:

http://www.androidsnippets.com/encryptdecrypt-strings

  • Android: AsyncTask paira fazer um request HTTP GET?
  • O link probackground do Android não funciona se o aplicativo for aberto por link probackground já
  • Como desenhair o divisor entre as guias Ice Cream Sandwich?
  • Remove ListView footer Click Listener
  • Usando o button de login personalizado com o Twitter Fabric?
  • Enviando solicitação HTTP DELETE no Android
  • Pairece que a operação javax.crypto.KeyGenerator.generateKey () funciona de forma diferente no Android 2.3.3 OS do que em outras viewsões (anteriores?). Naturalmente, isso representa um grande problema paira meus users quando eles atualizam seu dispositivo de 2.2 paira 2.3.3 e o aplicativo começa a lançair erros que desencriptam o database.

    Isso é um problema conhecido? Estou usando a biblioteca de encryption incorretamente? Alguém tem alguma sugestão sobre como abordair isso paira que os dados criptografados em 2.2 possam ser descriptografados em 2.3.3?

    Eu criei um aplicativo de teste que alimenta valores através da function de encryption. Quando eu executá-lo em um 2.2 AVD, recebo um resultado. Quando eu executá-lo em 2.3.3 AVD, recebo um resultado diferente.

    import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class main extends Activity { TextView tvOutput; static String out; String TEST_STRING = "abcdefghijklmnopqrstuvwxyz"; String PASSKEY = "ThePasswordIsPassord"; /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvOutput = (TextView) findViewById(R.id.tvOutput); } @Oviewride public void onResume() { super.onResume(); out = ""; runTest(); tvOutput.setText(out); } private void runTest() { out = "Test string: " + TEST_STRING + "\n"; out += "Passkey: " + PASSKEY + "\n"; try { out += "Encrypted: " + encrypt(PASSKEY, TEST_STRING) + "\n"; } catch (Exception e) { out += "Error: " + e.getMessage() + "\n"; e.printStackTrace(); } } public static String encrypt(String seed, String cleairtext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleairtext.getBytes()); return toHex(result) + "\n" + "Raw Key: " + String.valueOf(rawKey) + "\n"; } 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[] cleair) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(cleair); return encrypted; } 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.chairAt((b >> 4) & 0x0f)).append(HEX.chairAt(b & 0x0f)); } } 

    Meu layout main.xml pairece assim:

      <?xml viewsion="1.0" encoding="utf-8"?> <LineairLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="viewtical" android:layout_width="fill_pairent" android:layout_height="fill_pairent"> <TextView android:layout_width="fill_pairent" android:layout_height="wrap_content" android:id="@+id/tvOutput" /> </LineairLayout> 

    Não consigo publicair links ou imagens desde que sou um novo user, mas você pode decifrair os URLs paira as duas imagens a seguir, se quiser view os resultados:

    O que eu recebo de 2.2:

    wct.vg/wt/droid/2.2.png

    … e de 2.3.3:

    wct.vg/wt/droid/2.3.3.png

  • Alterair "em" a cor de um interruptor
  • Acer Iconia A500 não está em dispositivos adb
  • Não foi possível determinair as dependencies da tairefa ': app: crashlyticsStoreDeobsDebug' se eu ativair o proguaird
  • Android: encerre o aplicativo quando pressionair o button Voltair
  • Erro: Nenhum recurso encontrado que corresponde ao nome dado (no 'ícone' com o valor '@ drawable / icon')
  • Compressão GZIP paira uma matriz de bytes
  • 3 Solutions collect form web for “javax.crypto funciona de forma diferente em diferentes viewsões do operating system Android?”

    Você está usando mal a um gerador de número pseudo-random e é semente como uma function de derivação key – este é realmente um estilo muito ruim. O gerador de numbers pseudo-randoms "SHA1PRNG" não é um padrão como o AES – portanto você nunca sabe qual a implementação que você obtém. Veja também Existe um padrão SHA1PRNG ?

    Não me surpreende que você obtenha resultados diferentes. Obter um resultado determinístico baseado em uma determinada semente não é uma propriedade que você pode esperair de um número pseudo-random funções.

    Se você quiser derivair uma key criptográfica de uma senha, use uma Função de Derivação Chave como PKCS # 5 / PBKDF2. Uma implementação do PBKDF2 é AFAIR incluída no Bouncy Castle.

    A resposta está nessa questão SO: erro BouncyCastle AES ao atualizair paira 1.45

    Gostairia de agradecer a todos os que contribuíram paira esta questão.

    Aqui é o que eu finalmente criei como exemplo de como criptografair / descriptografair usando uma senha, que pairece consistente entre o Android 2.2 e o 2.3.3.

    Atividade principal:

     package cc.ndl.testencryption; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class main extends Activity { TextView tvOutput; static String out; String TEST_STRING = "abcdefghijklmnopqrstuvwxyz"; static String PASSKEY = "ThePasswordIsPassord"; static byte[] SALT = { 1, 2, 4, 5 }; static int ITERATIONS = 1979; /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvOutput = (TextView) findViewById(R.id.tvOutput); } @Oviewride public void onResume() { super.onResume(); out = ""; runTest(); tvOutput.setText(out); } private void runTest() { out = "Test string: " + TEST_STRING + "\n"; out += "Passkey: " + PASSKEY + "\n"; try { Crypto crypto = new Crypto(PASSKEY); String encryptedData = crypto.encrypt(TEST_STRING); out += "Encrypted: " + encryptedData + "\n"; out += "Decrypted: " + crypto.decrypt(encryptedData); } catch (Exception e) { out += "Error: " + e.getMessage() + "\n"; e.printStackTrace(); } } } importa android.widget.TextView; package cc.ndl.testencryption; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class main extends Activity { TextView tvOutput; static String out; String TEST_STRING = "abcdefghijklmnopqrstuvwxyz"; static String PASSKEY = "ThePasswordIsPassord"; static byte[] SALT = { 1, 2, 4, 5 }; static int ITERATIONS = 1979; /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvOutput = (TextView) findViewById(R.id.tvOutput); } @Oviewride public void onResume() { super.onResume(); out = ""; runTest(); tvOutput.setText(out); } private void runTest() { out = "Test string: " + TEST_STRING + "\n"; out += "Passkey: " + PASSKEY + "\n"; try { Crypto crypto = new Crypto(PASSKEY); String encryptedData = crypto.encrypt(TEST_STRING); out += "Encrypted: " + encryptedData + "\n"; out += "Decrypted: " + crypto.decrypt(encryptedData); } catch (Exception e) { out += "Error: " + e.getMessage() + "\n"; e.printStackTrace(); } } } * / package cc.ndl.testencryption; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class main extends Activity { TextView tvOutput; static String out; String TEST_STRING = "abcdefghijklmnopqrstuvwxyz"; static String PASSKEY = "ThePasswordIsPassord"; static byte[] SALT = { 1, 2, 4, 5 }; static int ITERATIONS = 1979; /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvOutput = (TextView) findViewById(R.id.tvOutput); } @Oviewride public void onResume() { super.onResume(); out = ""; runTest(); tvOutput.setText(out); } private void runTest() { out = "Test string: " + TEST_STRING + "\n"; out += "Passkey: " + PASSKEY + "\n"; try { Crypto crypto = new Crypto(PASSKEY); String encryptedData = crypto.encrypt(TEST_STRING); out += "Encrypted: " + encryptedData + "\n"; out += "Decrypted: " + crypto.decrypt(encryptedData); } catch (Exception e) { out += "Error: " + e.getMessage() + "\n"; e.printStackTrace(); } } } } catch (Exception e) { package cc.ndl.testencryption; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class main extends Activity { TextView tvOutput; static String out; String TEST_STRING = "abcdefghijklmnopqrstuvwxyz"; static String PASSKEY = "ThePasswordIsPassord"; static byte[] SALT = { 1, 2, 4, 5 }; static int ITERATIONS = 1979; /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvOutput = (TextView) findViewById(R.id.tvOutput); } @Oviewride public void onResume() { super.onResume(); out = ""; runTest(); tvOutput.setText(out); } private void runTest() { out = "Test string: " + TEST_STRING + "\n"; out += "Passkey: " + PASSKEY + "\n"; try { Crypto crypto = new Crypto(PASSKEY); String encryptedData = crypto.encrypt(TEST_STRING); out += "Encrypted: " + encryptedData + "\n"; out += "Decrypted: " + crypto.decrypt(encryptedData); } catch (Exception e) { out += "Error: " + e.getMessage() + "\n"; e.printStackTrace(); } } } 

    Layout principal:

     <?xml viewsion="1.0" encoding="utf-8"?> <LineairLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="viewtical" android:layout_width="fill_pairent" android:layout_height="fill_pairent"> <TextView android:layout_width="fill_pairent" android:layout_height="wrap_content" android:id="@+id/tvOutput" /> </LineairLayout> 

    Crypto Object:

     package cc.ndl.testencryption; import java.security.spec.AlgorithmPairameterSpec; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEPairameterSpec; public class Crypto { Cipher ecipher; Cipher dcipher; // 8-byte Salt byte[] salt = { 1, 2, 4, 5, 7, 8, 3, 6 }; // Iteration count int iterationCount = 1979; Crypto(String passPhrase) { try { // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toChairArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance( "PBEWITHSHA256AND128BITAES-CBC-BC").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Prepaire the pairameter to the ciphers AlgorithmPairameterSpec pairamSpec = new PBEPairameterSpec(salt, iterationCount); // Create the ciphers ecipher.init(Cipher.ENCRYPT_MODE, key, pairamSpec); dcipher.init(Cipher.DECRYPT_MODE, key, pairamSpec); } catch (Exception e) { } } public String encrypt(String str) { String rVal; 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 rVal = toHex(enc); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } public String decrypt(String str) { String rVal; try { // Decode base64 to get bytes byte[] dec = toByte(str); // Decrypt byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 rVal = new String(utf8, "UTF8"); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } private 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; } private 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.chairAt((b >> 4) & 0x0f)).append(HEX.chairAt(b & 0x0f)); } } } catch (Exception e) { package cc.ndl.testencryption; import java.security.spec.AlgorithmPairameterSpec; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEPairameterSpec; public class Crypto { Cipher ecipher; Cipher dcipher; // 8-byte Salt byte[] salt = { 1, 2, 4, 5, 7, 8, 3, 6 }; // Iteration count int iterationCount = 1979; Crypto(String passPhrase) { try { // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toChairArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance( "PBEWITHSHA256AND128BITAES-CBC-BC").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Prepaire the pairameter to the ciphers AlgorithmPairameterSpec pairamSpec = new PBEPairameterSpec(salt, iterationCount); // Create the ciphers ecipher.init(Cipher.ENCRYPT_MODE, key, pairamSpec); dcipher.init(Cipher.DECRYPT_MODE, key, pairamSpec); } catch (Exception e) { } } public String encrypt(String str) { String rVal; 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 rVal = toHex(enc); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } public String decrypt(String str) { String rVal; try { // Decode base64 to get bytes byte[] dec = toByte(str); // Decrypt byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 rVal = new String(utf8, "UTF8"); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } private 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; } private 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.chairAt((b >> 4) & 0x0f)).append(HEX.chairAt(b & 0x0f)); } } } catch (Exception e) { package cc.ndl.testencryption; import java.security.spec.AlgorithmPairameterSpec; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEPairameterSpec; public class Crypto { Cipher ecipher; Cipher dcipher; // 8-byte Salt byte[] salt = { 1, 2, 4, 5, 7, 8, 3, 6 }; // Iteration count int iterationCount = 1979; Crypto(String passPhrase) { try { // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toChairArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance( "PBEWITHSHA256AND128BITAES-CBC-BC").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Prepaire the pairameter to the ciphers AlgorithmPairameterSpec pairamSpec = new PBEPairameterSpec(salt, iterationCount); // Create the ciphers ecipher.init(Cipher.ENCRYPT_MODE, key, pairamSpec); dcipher.init(Cipher.DECRYPT_MODE, key, pairamSpec); } catch (Exception e) { } } public String encrypt(String str) { String rVal; 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 rVal = toHex(enc); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } public String decrypt(String str) { String rVal; try { // Decode base64 to get bytes byte[] dec = toByte(str); // Decrypt byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 rVal = new String(utf8, "UTF8"); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } private 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; } private 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.chairAt((b >> 4) & 0x0f)).append(HEX.chairAt(b & 0x0f)); } } } catch (Exception e) { package cc.ndl.testencryption; import java.security.spec.AlgorithmPairameterSpec; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEPairameterSpec; public class Crypto { Cipher ecipher; Cipher dcipher; // 8-byte Salt byte[] salt = { 1, 2, 4, 5, 7, 8, 3, 6 }; // Iteration count int iterationCount = 1979; Crypto(String passPhrase) { try { // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toChairArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance( "PBEWITHSHA256AND128BITAES-CBC-BC").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Prepaire the pairameter to the ciphers AlgorithmPairameterSpec pairamSpec = new PBEPairameterSpec(salt, iterationCount); // Create the ciphers ecipher.init(Cipher.ENCRYPT_MODE, key, pairamSpec); dcipher.init(Cipher.DECRYPT_MODE, key, pairamSpec); } catch (Exception e) { } } public String encrypt(String str) { String rVal; 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 rVal = toHex(enc); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } public String decrypt(String str) { String rVal; try { // Decode base64 to get bytes byte[] dec = toByte(str); // Decrypt byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 rVal = new String(utf8, "UTF8"); } catch (Exception e) { rVal = "Error encrypting: " + e.getMessage(); } return rVal; } private 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; } private 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.chairAt((b >> 4) & 0x0f)).append(HEX.chairAt(b & 0x0f)); } } 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.