我正在尝试使用Sharepreferences进行注册并登录系统。我也要用 杰森。
让我直接回答这个问题。
要通过SharedPreferences访问数据,我们需要“键”。
这意味着每次用户注册时,我都需要为每个用户的身份提供密钥。
我如何制作代码以自动为用户ID创建密钥?
或者我访问方式有误吗?
对不起,我的英语要求和解释,谢谢!
答案 0 :(得分:1)
您可以从用户名和密码中获取sha1值,并将其保存在SP中作为注册过程,并且可以获取登录过程的密钥并获取用户配置文件的值:
private static String encryptPassword(String password)
{
String sha1 = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return sha1;
}
private static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
答案 1 :(得分:0)
您可以通过多种方式执行此操作,这在很大程度上取决于您的安全性要求等。但是,仅仅是为了让您起步。生成唯一密钥:
val uniqueKey = "${Random.nextLong()} $userName ${System.nanoTime()}"
并将其用于您的偏好:
val usersAge = prefs.get("${uniqueKey}Age", -1)
val usersFavColor = prefs.get("${uniqueKey}FavColor", "Red")
您需要将密钥存储在某个位置,然后根据该用户进行查找....