簡體   English   中英

Android加密

[英]Android encryption

我正在開發一個Android應用程序,我需要在它的一個方面使用加密。 我對使用哪種算法(AES,DES,RSA等)無動於衷。 我知道Java有一個加密包,但我根本不熟悉它。 有人可以發布一個關於如何進行加密/解密功能的例子嗎?

java AES庫有一個缺陷,它允許在適當的情況下,一個監聽器解密發送的數據包。 請參閱填充Oracle漏洞利用工具與Apache MyFaces

那就是說看看這個問題Java 256bit AES加密

Bouncy Castle AES示例被盜: http//www.java2s.com/Code/Java/Security/EncryptionanddecryptionwithAESECBPKCS7Padding.htm

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());    
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 
                 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 
                 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 
                 0x15, 0x16, 0x17 };

    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

    System.out.println(new String(input));

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    System.out.println(new String(cipherText));
    System.out.println(ctLength);

    // decryption pass
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
    int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    System.out.println(new String(plainText));
    System.out.println(ptLength);
  }
}

看看我在這里Android數據庫加密的答案。 它包含2個文件,您可以將這些文件包含在需要加密數據存儲的任何應用程序中。

我還會查看隱藏,看它是否適合你的賬單。 它有一個易於使用的API,它抽象了加密細節: https//github.com/facebook/conceal/

考慮到在Android中加密和解密數據的開銷,我設計了一個僅依賴於Android和Java本機庫的庫,以使過程盡可能簡單。

要安裝,請使用jcenter分發中心。 在gradle上:

compile 'com.tinmegali.android:mcipher:0.4'

用法

String ALIAS = "alias"
MEncryptor encryptor = new MEncryptorBuilder( ALIAS ).build();
MDecryptor decryptor = new MDecryptorBuilder( ALIAS ).build();

String toEncrypt = "encrypt this string";
// encrypting
String encrypted = encryptor.encryptString( toEncrypt, this );

// decrypting
String decrypted = decryptor.decryptString( encrypted, this );

MCipher與SDK 19+兼容,它自動適應較小和較大的數據塊。 默認情況下,它為SDK 23+使用AES/GCM/NoPadding ,對舊版本使用RSA/ECB/PKCS1Padding

MCipher在Github上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM