Encrypt stored data in Android

public static byte[] encrypt() throws Exception {
String seed = "SuperSecretPassword";
String plaintext = "This is insecure data!";

//API for generating symmetric cryptographic keys
KeyGenerator keygen = KeyGenerator.getInstance("AES");

//Returns a new instance of SecureRandom that utilizes the
//SHA1 algorithm.
SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG");

//Reseeds this SecureRandom instance with the specified seed.
secrand.setSeed(seed.getBytes());

//Initializes this KeyGenerator instance for the specified
//key size (in bits) using the specified randomness source.
keygen.init(128, secrand);
//Generates a secret key.
SecretKey seckey = keygen.generateKey();
//Returns the encoded form of the key.
byte[] rawKey = seckey.getEncoded();

//Create a new SecretKeySpec for the key data and AES algorithm.
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
//Creates a new Cipher for the specified transformation.
//The installed providers are searched in order for an
//implementation of the specified transformation.
//The first found provider providing the transformation
//is used to create the cipher.
Cipher cipher = Cipher.getInstance("AES");

//Initializes this cipher instance with the specified key.
//The cipher is initialized for the specified operational
//mode (one of: encryption, decryption, key wrapping or key unwrapping)
//depending on opmode.
//If this cipher instance needs any algorithm parameters
//or random values that the specified key cannot provide,
//the underlying implementation of this cipher is supposed
//to generate the required parameters (using its provider or random values).
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

//Finishes a multi-part transformation (encryption or decryption).
//Processes the bytes in input buffer, and any bytes that
//have been buffered in previous update calls.
byte[] encrypted = cipher.doFinal(plaintext.getBytes());

return encrypted;
}


解密只需要该这一句
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值