2015-05-04 111 views
0

我正在使用ormlite对我的文本进行加密的android应用程序,所以如果任何人从外部获取数据库文件,他将无法读取它没有解密它。我主要关心的是使用base64加密数据,当我想读取它应解密的数据。我已经阅读了base64链接中的一些示例代码,请向我建议在将文本保存到数据库之前对其进行加密的方式,并检索它应该解密的时间。使用Base64在ORMLITE中对文本进行编码/解码

// Sending side 
byte[] data = text.getBytes("UTF-8"); 
String base64 = Base64.encodeToString(data, Base64.DEFAULT); 

// Receiving side 
byte[] data = Base64.decode(base64, Base64.DEFAULT); 
String text = new String(data, "UTF-8"); 
+3

加密和编码有很大的区别。请确保您的数据不敏感。检查这篇文章的更多加密细节http://stackoverflow.com/questions/1205135/how-to-encrypt-string-in-java – Stefan

+0

其实我正在寻找任何机制来加密和解密我的文本ormlite数据库。我只需要做一些可以在db中加密我的数据的东西,并且在接收它应该解密的时间。 –

+1

是的,编码和加密的区别在于:sombody总是可以解码你的字符串,所以它不安全。加密。另一个人将需要一个加密密钥来解密它。 – Stefan

回答

1

您可以使用此代码进行加密和解密。

我在这里使用3DES加密方案。我希望它能帮助你。

public PasswordEncryption_TrippleDES() throws Exception { 
     myEncryptionKey = //your encryption key 
     myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME; 
     arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT); 
     ks = new DESedeKeySpec(arrayBytes); 
     skf = SecretKeyFactory.getInstance(myEncryptionScheme); 
     cipher = Cipher.getInstance(myEncryptionScheme); 
     key = skf.generateSecret(ks); 
    } 

    public String encrypt(String unencryptedString) { 
     String encryptedString = null; 
     try { 
      cipher.init(Cipher.ENCRYPT_MODE, key); 
      byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT); 
      byte[] encryptedText = cipher.doFinal(plainText); 
      encryptedString = new String(Base64.encodeBase64(encryptedText)); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return encryptedString; 
    } 

    public String decrypt(String encryptedString) { 
     String decryptedText=null; 
     try { 
      cipher.init(Cipher.DECRYPT_MODE, key); 
      byte[] encryptedText = Base64.decodeBase64(encryptedString); 
      byte[] plainText = cipher.doFinal(encryptedText); 
      decryptedText= new String(plainText); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return decryptedText; 
    }