2015-05-04 94 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; 
    } 
相關問題