以下是安卓代码:
MessageDigest md = MessageDigest.getInstance("SHA1");//No I18N
byte[] messageDigest = md.digest(plainText.getBytes("UTF-8"));
PrivateKeyEntry pKey = (PrivateKeyEntry) Application.getInstance(appcontext)
.getKeyStore()
.getEntry(KEY_STORE_ALIAS, null);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pKey.getPrivateKey());
byte[] encBytes = cipher.doFinal(messageDigest);
String encryptedData = new String(Base64.encode(encBytes, Base64.DEFAULT), "UTF-8");
return encryptedData;
以下是 uwp 代码:
IBuffer dataBuffer = Encoding.UTF8.GetBytes(plainText).AsBuffer();
IBuffer KeyPairBuffer = Convert.FromBase64String(keyPairString).AsBuffer();
AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
CryptographicKey cryptographicKey = asymmetricKeyAlgorithm.ImportKeyPair(KeyPairBuffer);
HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
IBuffer hashedBuffer = hashAlgorithm.HashData(dataBuffer);
System.Diagnostics.Debug.WriteLine(Convert.ToBase64String(hashedBuffer.ToArray()));
var buffer = CryptographicEngine.SignHashedData(cryptographicKey, hashedBuffer);
return Convert.ToBase64String((buffer.ToArray()));'
安卓代码工作正常,但 UWP 代码无法正常工作。提前感谢您的帮助。
我得到了不同的异常,例如错误:签名验证失败,javax.crypto.BadPaddingException:解密错误,javax.crypto.IllegalBlockSizeException:数据不得超过256字节 -
我在 UWP 中测试了代码片段,无法重现您的问题。由于您的代码片段不完整,以下是可以在我这边成功运行的完整代码片段。
string plainText = "test";
IBuffer dataBuffer = Encoding.UTF8.GetBytes(plainText).AsBuffer();
//IBuffer KeyPairBuffer = Convert.FromBase64String(keyPairString).AsBuffer();
AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
CryptographicKey cryptographicKey = asymmetricKeyAlgorithm.CreateKeyPair(512);
//CryptographicKey cryptographicKey = asymmetricKeyAlgorithm.ImportKeyPair(buffKeyPair);
HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
IBuffer hashedBuffer = hashAlgorithm.HashData(dataBuffer);
System.Diagnostics.Debug.WriteLine(Convert.ToBase64String(hashedBuffer.ToArray()));
var buffer = CryptographicEngine.SignHashedData(cryptographicKey, hashedBuffer);
特别是,您在这里提到的异常看起来像 Java 异常,而不是 c#。因此,请首先确保哪个代码行抛出了异常。然后检查keyPairString
是否正确。请注意,典型的密钥大小为 512、1024、2048 或 4096 位。
有关更多详细信息,请参阅官方教程。