我正在寻找加密用户输入用户名和密码时生成的访问令牌。我在这里问的问题是这样做的不同方式是什么,社区认为最好的方法是什么。我看过Cryptography和Keystore,但不确定这些是否是正确的方法?我是加密菜鸟,所以任何文档都会非常有用。
非常感谢你:D
答案 0 :(得分:0)
请尝试使用android SecretKeySpec类
用于加密
public void setPassCode(String value) throws Exception {
try {
SecretKeySpec sks = null;
sks = getEncryptKey();
byte[] userLatENC=null;
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE,sks );
userLatENC = c.doFinal(value.getBytes());
passCode = Base64.encodeToString(userLatENC, Base64.DEFAULT);
} catch (Exception e) {
throw e;
}
}
用于解密
public String getPassCode() throws Exception {
SecretKeySpec sks = null;
try {
String encVal = "pass_code";
if (encVal.isEmpty()) {
return encVal;
}
sks = getDecryptKey();
byte[] latDEC=null;
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, sks);
latDEC = c.doFinal(Base64.decode(encVal, Base64.DEFAULT));
return new String(latDEC);
} catch (Exception e) {
throw e;
}
}
获取加密密钥
private SecretKeySpec getEncryptKey() throws Exception{
SecretKeySpec sks = null;
SecretKey key =null;
byte[] keyToSave;
try {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed("any data used as random seed".getBytes());
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128, sr);
key= kg.generateKey();
keyToSave =key.getEncoded();
sks = new SecretKeySpec(keyToSave, "AES");
ks.load(null,null);
ks.setKeyEntry("aliasKey",key,null, null);
FileOutputStream ksout = context.openFileOutput("keystore_android", Context.MODE_PRIVATE);
ks.store(ksout, null);
ksout.close();
return sks;
} catch (Exception e) {
throw e;
}
}
对于解密密钥
private SecretKeySpec getDecryptKey() throws Exception{
SecretKeySpec sks = null;
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream fis = null;
fis = context.openFileInput("keystore_android");
keyStore.load(fis,null);
sks=new SecretKeySpec((keyStore.getKey("aliasKey", null)).getEncoded(), "AES");
return sks;
} catch (Exception e) {
throw e;
}
}