【发布时间】:2022-01-15 21:06:37
【问题描述】:
我目前正忙于 Androidkeystore 公钥/私钥加密。我正在捕获用户数据,在将其上传到 firebase 之前,我想对其进行加密。我在https://dzone.com/articles/xamarin-android-asymmetric-encryption-without-any这个链接的帮助下做到了。
我在设备上捕获了用户登录凭据和用户数据,并在将数据上传到 Firebase 之前使用公钥对数据进行了加密。然后我从 firebase 检索数据并使用私钥成功解密数据。现在,当我在其他设备上登录时,我无法解密数据。这可能是因为我没有以前设备的密钥对吗?
您很可能会注意到,我对这个主题知之甚少。有什么可能的方法可以实现上述问题。
下面是我使用的代码:
初始化 KeyStore
public PlatformEncryptionKeyHelper(Context context, string keyName)
{
_context = context;
_keyName = keyName.ToLowerInvariant();
_androidKeyStore = KeyStore.GetInstance(KEYSTORE_NAME);
_androidKeyStore.Load(null);
}
生成密钥对
var builder = new KeyGenParameterSpec.Builder(_keyName, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
.SetBlockModes(KeyProperties.BlockModeEcb)
.SetEncryptionPaddings(KeyProperties.EncryptionPaddingRsaPkcs1)
.SetRandomizedEncryptionRequired(false).SetKeySize(KeySize);
keyGenerator.Initialize(builder.Build());
}
keyGenerator.GenerateKeyPair();
获取公钥
public IKey GetPublicKey()
{
if (!_androidKeyStore.ContainsAlias(_keyName))
return null;
return _androidKeyStore.GetCertificate(_keyName)?.PublicKey;
}
获取私钥
public IKey GetPrivateKey()
{
if (!_androidKeyStore.ContainsAlias(_keyName))
return null;
return _androidKeyStore.GetKey(_keyName, null);
}
用法
_encryptionKeyHelper = new PlatformEncryptionKeyHelper(Application.Context, KeyStoreName);
_encryptionKeyHelper.CreateKeyPair();
_privateKey = _encryptionKeyHelper.GetPrivateKey();
_publicKey = _encryptionKeyHelper.GetPublicKey();
提前致谢!
【问题讨论】:
标签: c# android xamarin encryption