我正在开发wp8应用程序。我在第一次登录请求中向服务器发送公钥。响应服务器发送令牌(其简单的base64字符串,大约1200-1300个字符),我需要用私钥签名并在下一个请求中发送回服务器。现在服务器验证该令牌我在第一个请求中发送了相应的公钥。我有工作的java代码,它做了以上的事情。
String privateKey = sharedPref.getString("privateKey", "");
byte [] decoded = Base64.decode(privateKey, Base64.NO_WRAP);
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
PrivateKey privateKeyNew = kf.generatePrivate(keySpec);
String tokenSp = sharedPref.getString("token", "");
byte[] tokenBytes = tokenSp.getBytes();
Signature dsa = Signature.getInstance("SHA1withRSA");
dsa.initSign(privateKeyNew);
dsa.update(tokenBytes);
byte[] signedData = dsa.sign();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(tokenBytes);
baos.write(signedData);
byte[] finalout = baos.toByteArray();
signedToken = new String(Base64.encode(finalout, 0, finalout.length, Base64.NO_WRAP));
我希望在c#中实现相同。我写的代码是:
UnicodeEncoding ByteConverter = new UnicodeEncoding();
CspParameters parameters = new CspParameters();
parameters.KeyContainerName = "MyContainer";
RSACryptoServiceProvider obj = new RSACryptoServiceProvider(parameters);
byte[] dataToEncrypt=ByteConverter.GetBytes(s[0]);
byte[] SignedData=obj.SignData(dataToEncrypt, "SHA256");
MemoryStream stream = new MemoryStream();
stream.Write(dataToEncrypt,0,dataToEncrypt.Count());
stream.Write(SignedData,0,SignedData.Count());
byte[] finalBytesToSend = stream.ToArray();
string s2 = Convert.ToBase64String(finalBytesToSend);
return s2;
对于服务器,我发送“SHA256”作为公钥进行验证。它是否更正了我在c#中所做的事情?
答案 0 :(得分:0)
我相信你需要的是下面的东西。您可能需要检查publicKeyXml
并对格式进行一些处理。
// create a RSA provider with a 1024 bits key
using(RSACryptoServiceProvider rsaProv = new RSACryptoServiceProvider(1024))
{
// export public key and send it to server to obtain base64 token
string publicKeyXml = rsaProv.ToXmlString(false);
string base64TokenFromServer = GetTokenFromServer(publicKeyXml);
// decode base64 token
byte[] tokenBytes = Convert.FromBase64String(base64TokenFromServer);
// sign token bytes using RSA provider's private key and SHA1
byte[] tokenSignatureBytes;
using (var ms = new MemoryStream(tokenBytes))
{
tokenSignatureBytes = rsaProv.SignData(ms, SHA1.Create());
}
// concat token bytes and signature bytes
byte[] finalOut;
using (var ms = new MemoryStream())
{
ms.Write(tokenBytes, 0, tokenBytes.Length);
ms.Write(tokenSignatureBytes, 0, tokenSignatureBytes.Length);
ms.Flush();
finalOut = ms.ToArray();
}
// encode final out to base64
string signedToken = Convert.ToBase64String(finalOut);
}