I'm having a bit of an issue. I'm trying to write a client-server application (more a POC really), with the client requesting the public key from the server, the server then generates this key AsymmetricCipherKeyPair
with the following
private static AsymmetricCipherKeyPair GenerateKeyPair() {
RsaKeyPairGenerator g = new RsaKeyPairGenerator();
g.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
var pair = g.GenerateKeyPair();
return pair;
}
This generates correctly and can encrypt and encrypt correctly(on the server side, but that defeats the purpose)
So I then send a serialized public key to the client
private static byte[] SerialisePublic(AsymmetricCipherKeyPair keypair) {
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
return serializedPublicBytes;
}
private static void SendBytes(TcpClient client, byte[] send) {
NetworkStream stream = client.GetStream();
stream.Write(send, 0, send.Length);
stream.Flush();
}
However now, when I try to initialise the keypair
on the otherside, I need a private key (which also defeats the purpose)
I tried the following
static string EncryptString(string key, string message) {
string res = "";
using (var rsa = new RSACryptoServiceProvider(128)) {
try {
rsa.FromXmlString(string.Format("<RSAKeyValue>{0}</RSAKeyValue>", key));
byte[] b = Encoding.ASCII.GetBytes(message);
var encryptedData = rsa.Encrypt(b, true);
var base64Encrypted = Convert.ToBase64String(encryptedData);
res = base64Encrypted;
}
catch (Exception ex) {
}
finally {
rsa.PersistKeyInCsp = false;
}
return res;
}
}
(In the absence of a keypair, I thought I could hack it)
however as this does not contain nearly half the information required for encryption, it fails, hard.
I'd like to keep to using Bouncy Castle if possible, however I am open to suggestions.
Thanks in advance.
UPDATE
Both client and server are being written in C#
Update 2 (thanks Andrew)
This will initialise the RsaEngine
with the public key provide by the server(or at least is should) (This didn't work, don't use it)
static byte[] EncryptBytes(byte[] key, byte[] message) {
byte[] res = null;
AsymmetricKeyParameter ic = (AsymmetricKeyParameter)PublicKeyFactory.CreateKey(key);
RsaEngine e = new RsaEngine();
e.Init(true, ic);
res = e.ProcessBlock(message, 0, message.Length);
return res;
}
Update 3
So that didn't work, the PublicKeyFactory
doesn't seem to like the returned key
throwing: Unknown object in GetInstance: Org.BouncyCastle.Asn1.DerApplicationSpecific
I think it could be an issue in the Serialisation on server side and then the deserialisation on the client side.
So maybe a CryptoStream
for the transmission of a public key and additional authentication (passphrase, secret knock or a joke) when a client connects to a server.
stay tuned