我正在嘗試使用BouncyCastle生成公鑰(因爲我使用的是Unity,並且無法訪問ECDiffieHellmanCng),然後將公鑰傳輸到服務器它使用ECDiffieHellmanCng進行密鑰處理。 服務器拒絕我的密鑰,看起來是因爲它的長度小。 ECDiffieHellmanCng生成的公鑰與Bouncy城堡生成的公鑰相比,其大小要大得多。爲什麼BouncyCastle生成的密鑰小於.Net的ECDiffieHellmanCng
有沒有辦法在充氣城堡中生成一個更大的鑰匙?
我試着改變keybit大小,但得到一個錯誤:InvalidParameterException:未知的密鑰大小。
密鑰BouncyCastle的生成:
3059301306072A8648CE3D020106082A8648CE3D03010703420004272F71C1D8B3DC0A7FCB1E9650EEF64EA8F639BEC97D49F8848455C2F5869F7324332D188129C84727F834EE7EE7D8EB7DFC8D40CD4ED219A4FBCEF6C15200F3
密鑰ECDiffieHellmanCng生成:
45434B35420000000055CC8665A66A7CDF2E9BF7C69A25B322C72CDBDB1EA8F348050B0A7CF32F9AAD8 90EA513583367977D5157B2F7FBF55661C9AE2DBAF09B1DC1EA8F193688C3C09501BEE326867ABCB41CA1029F66AF888649F0A6C0674D19670CF32461BA7B3867C1623D68829A7A9A7F1CFC6F5DB99E13C8D960AEF6F5CDAB5B3B62ED6CBEC7222C9F
這裏是代碼多數民衆贊成產生充氣城堡關鍵:
const string Algorithm = "ECDH";
const int KeyBitSize = 256;
const int NonceBitSize = 128;
const int MacBitSize = 128;
const int DefaultPrimeProbability = 30;
IAsymmetricCipherKeyPairGenerator aliceKeyGen = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
DHParametersGenerator aliceGenerator = new DHParametersGenerator();
aliceGenerator.Init(KeyBitSize, DefaultPrimeProbability, new SecureRandom());
DHParameters aliceParameters = aliceGenerator.GenerateParameters();
KeyGenerationParameters aliceKGP = new DHKeyGenerationParameters(new SecureRandom(), aliceParameters);
aliceKeyGen.Init(aliceKGP);
AsymmetricCipherKeyPair aliceKeyPair = aliceKeyGen.GenerateKeyPair();
IBasicAgreement aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);
aliceKeyAgree.Init(aliceKeyPair.Private);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aliceKeyPair.Public);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
string serializedPublic = AsString(serializedPublicBytes);
public static string AsString(byte[] bytes, bool keepDashes = false)
{
string hex = BitConverter.ToString(bytes);
return (keepDashes ? hex : hex.Replace("-", ""));
}
我也試過Mentalis.org DH庫,這給了我更大的關鍵,但仍然只是一個頭發剪得太短。從mentalis.org庫
// create a new DH instance
DiffieHellman dh1 = new DiffieHellmanManaged();
// generate the public key of the first DH instance
byte[] ke1 = dh1.CreateKeyExchange();
string publicKeyString = AsString(ke1);
重點:
5F4542F9A8F5636ECCBBAC38238C97ABE757B8F65E25B181BCF41C58985E699EFD6B9606B99F7074717E83F7AC1B5E97DFF6DBA94876F74645F25F0D7FAA1528898C1BD0BB568DF15A98724093766B213769893A05B47E40410B0F395C834F68F57B2EE01852895D912C1D56675A7D8C5367B5E06DE08AAA18CBB4C69F3AE142
它不是這麼多的大小,但有關格式。 Bouncycastle返回公鑰的標準化編碼,但您的ECDiffieHellmanCng是Microsoft專有的blob。Mentalis結果根本不* ECDH值。 –
嗯,有沒有辦法使用ECDiffieHellmanCng以外的東西來獲得Microsoft專有的blob?我無法訪問它。 – Snipe3000
哦,部分尺寸差異是你在CNG有一個NIST P-521密鑰,而BouncyCastle有一個NIST P-256密鑰。 (0x354B4345 == BCRYPT_ECDH_PUBLIC_P521_MAGIC) – bartonjs