[英]java cipher to c# equivalent
我非常感謝任何幫助。 我正在嘗試將 rsa cryptor java 實現轉換為 c#。 我需要加密信用卡數據。 我使用的平台為 javascript 和 android 提供了加密 SDK,但我需要一個 C# 實現。
try {
cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "SC");
} catch (SecurityException se) {
//workaround for tests
Log.i("Moip SDK", "No SC provider, running test profile");
cipher = Cipher.getInstance("RSA");
}
BufferedReader pemReader = null;
pemReader = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(publicKey.getBytes("UTF-8"))));
StringBuffer content = new StringBuffer();
String line = null;
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----END PUBLIC KEY") != -1) {
break;
}
content.append(line.trim());
}
break;
}
}
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT))));
byte[] cipherText = cipher.doFinal(toHash().getBytes());
return Base64.encodeToString(cipherText, Base64.DEFAULT);
我創建的代碼查看了 java 中的實現,它可以工作但無法在平台上解密,我一定是忘記了一些東西。 我的實現:
private string Payload(string number, string expirationMonth, string expirationYear, string cvc) {
return String.Join(
"&",
new List<string> {
$"number={number}",
$"cvc={cvc}",
$"expirationMonth={expirationMonth}",
$"expirationYear={expirationYear}",
}
);
}
private string Encrypt(string key, string payload) {
var publicKey = $"<RSAKeyValue><Modulus>{key}</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
var rsa = new RSACryptoServiceProvider(2048);
rsa.FromXmlString(publicKey);
var encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(payload), RSAEncryptionPadding.Pkcs1);
rsa.Dispose();
return Convert.ToBase64String(encryptedData);
}
var payload = Payload(number, expirationMonth, expirationYear, cvc);
hash = Encrypt(ClientManager.Environment.publicKeyCreditCard, payload);
歡迎使用 Stackoverflow。 我運行你的代碼,我可以成功地在兩個平台(Java 和 C#)上加密和解密。
因此,在我看來,在 C# 上進行加密時解密失敗的唯一原因是您沒有正確轉換公鑰。
我建議使用(因為它是公鑰)像https://superdry.apphb.com/tools/online-rsa-key-converter這樣的在線轉換器。
只需像這樣復制下方輸入文本區域“PEM to XML”中的公鑰(它是一個不安全的512 位 RSA 密鑰,因此它會比您的密鑰短):
-----BEGIN PUBLIC KEY-----" +
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJn4LYaoLyuT+pD9NKI8wOvPrRjMIxGn
HbqIxUrpGsyj162fEOV4836oCZg0N8HFnt4Vivdjt8/7ZgLjeOygNGUCAwEAAQ==
-----END PUBLIC KEY-----
然后按“轉換” - 在下面你會得到 xml 格式的公鑰:
<RSAKeyValue><Modulus>mfgthqgvK5P6kP00ojzA68+tGMwjEacduojFSukazKPXrZ8Q5XjzfqgJmDQ3wcWe3hWK92O3z/tmAuN47KA0ZQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
您必須向 C# 方法提供的部分鍵位於 Modulus 之后:
mfgthqgvK5P6kP00ojzA68+tGMwjEacduojFSukazKPXrZ8Q5XjzfqgJmDQ3wcWe3hWK92O3z/tmAuN47KA0ZQ==
您應該注意該值 - 在大多數情況下它是“AQAB”,但如果您收到另一個值,您必須在 C# 中調整源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.