Android 数据加密
时间: 2023-11-21 20:58:53 浏览: 34
Android数据加密可以使用对称加密和非对称加密两种方式。其中对称加密包括DES、3DES和AES三种算法,非对称加密包括RSA算法。以下是Android数据加密的一些例子:
1. 对称加密之AES加密
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
private static final String KEY = "1234567890123456"; // 密钥长度必须是16位
public static String encrypt(String content) throws Exception {
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(content.getBytes());
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}
public static String decrypt(String content) throws Exception {
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedBytes = Base64.decode(content, Base64.DEFAULT);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
```
2. 非对称加密之RSA加密
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSAUtil {
private static final String ALGORITHM = "RSA";
private static final int KEY_SIZE = 1024;
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
return keyPairGenerator.generateKeyPair();
}
public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(content);
}
public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(content);
}
}
```