Skip to content

Commit af0babf

Browse files
authored
[C#][netcore] various improvements in HttpSigningConfiguration.cs (#10941)
* various improvements in HttpSigningConfiguration.cs * update returns in xml comments
1 parent ca84887 commit af0babf

7 files changed

Lines changed: 391 additions & 315 deletions

File tree

modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache

Lines changed: 49 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
{{>partial_header}}
2+
13
using Newtonsoft.Json;
24
using Newtonsoft.Json.Serialization;
35
using System;
@@ -82,7 +84,7 @@ namespace {{packageName}}.Client
8284
/// <param name="method">HTTP method</param>
8385
/// <param name="path">Path</param>
8486
/// <param name="requestOptions">Request options</param>
85-
/// <returns></returns>
87+
/// <returns>Http signed headers</returns>
8688
internal Dictionary<string, string> GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions)
8789
{
8890
const string HEADER_REQUEST_TARGET = "(request-target)";
@@ -133,7 +135,7 @@ namespace {{packageName}}.Client
133135
}
134136
else
135137
{
136-
httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]);
138+
httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]);
137139
}
138140
#else
139141
if (parameter.Value.Count > 1)
@@ -178,7 +180,6 @@ namespace {{packageName}}.Client
178180
throw new Exception(string.Format("{0} not supported", HashAlgorithm));
179181
}
180182

181-
182183
foreach (var header in HttpSigningHeader)
183184
{
184185
if (header.Equals(HEADER_REQUEST_TARGET))
@@ -236,7 +237,6 @@ namespace {{packageName}}.Client
236237
foreach (var keyVal in HttpSignatureHeader)
237238
{
238239
headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value));
239-
240240
}
241241
//Concatenate headers value separated by new line
242242
var headerValuesString = string.Join("\n", headerValuesList);
@@ -252,7 +252,11 @@ namespace {{packageName}}.Client
252252
{
253253
headerSignatureStr = GetECDSASignature(signatureStringHash);
254254
}
255-
var cryptographicScheme = "hs2019";
255+
else
256+
{
257+
throw new Exception(string.Format("Private key type {0} not supported", keyType));
258+
}
259+
const string cryptographicScheme = "hs2019";
256260
var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"",
257261
KeyId, cryptographicScheme);
258262

@@ -268,9 +272,7 @@ namespace {{packageName}}.Client
268272

269273
authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"",
270274
headersKeysString, headerSignatureStr);
271-
272275
HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue);
273-
274276
return HttpSignedRequestHeader;
275277
}
276278

@@ -302,23 +304,26 @@ namespace {{packageName}}.Client
302304
var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1);
303305
return Convert.ToBase64String(signedbytes);
304306
}
305-
return string.Empty;
307+
else
308+
{
309+
return string.Empty;
310+
}
306311
}
307312

308313
/// <summary>
309314
/// Gets the ECDSA signature
310315
/// </summary>
311316
/// <param name="dataToSign"></param>
312-
/// <returns></returns>
317+
/// <returns>ECDSA signature</returns>
313318
private string GetECDSASignature(byte[] dataToSign)
314319
{
315320
if (!File.Exists(KeyFilePath))
316321
{
317322
throw new Exception("key file path does not exist.");
318323
}
319324

320-
var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----";
321-
var ecKeyFooter = "-----END EC PRIVATE KEY-----";
325+
const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----";
326+
const string ecKeyFooter = "-----END EC PRIVATE KEY-----";
322327
var keyStr = File.ReadAllText(KeyFilePath);
323328
var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim();
324329
var keyBytes = System.Convert.FromBase64String(ecKeyBase64String);
@@ -355,10 +360,9 @@ namespace {{packageName}}.Client
355360
#else
356361
throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above");
357362
#endif
358-
359363
}
360364

361-
private byte[] ConvertToECDSAANS1Format(byte[] signedBytes)
365+
private byte[] ConvertToECDSAANS1Format(byte[] signedBytes)
362366
{
363367
var derBytes = new List<byte>();
364368
byte derLength = 68; //default length for ECDSA code signing bit 0x44
@@ -481,7 +485,7 @@ namespace {{packageName}}.Client
481485
byte[] salt = new byte[saltstr.Length / 2];
482486
for (int i = 0; i < salt.Length; i++)
483487
salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16);
484-
if (!(str.ReadLine() == ""))
488+
if (str.ReadLine() != "")
485489
{
486490
return null;
487491
}
@@ -512,7 +516,7 @@ namespace {{packageName}}.Client
512516

513517
private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
514518
{
515-
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
519+
byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ;
516520
517521
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
518522
MemoryStream mem = new MemoryStream(privkey);
@@ -549,40 +553,40 @@ namespace {{packageName}}.Client
549553

550554
//------ all private key components are Integer sequences ----
551555
elems = GetIntegerSize(binr);
552-
MODULUS = binr.ReadBytes(elems);
556+
bytesModulus = binr.ReadBytes(elems);
553557

554558
elems = GetIntegerSize(binr);
555-
E = binr.ReadBytes(elems);
559+
bytesE = binr.ReadBytes(elems);
556560

557561
elems = GetIntegerSize(binr);
558-
D = binr.ReadBytes(elems);
562+
bytesD = binr.ReadBytes(elems);
559563

560564
elems = GetIntegerSize(binr);
561-
P = binr.ReadBytes(elems);
565+
bytesP = binr.ReadBytes(elems);
562566

563567
elems = GetIntegerSize(binr);
564-
Q = binr.ReadBytes(elems);
568+
bytesQ = binr.ReadBytes(elems);
565569

566570
elems = GetIntegerSize(binr);
567-
DP = binr.ReadBytes(elems);
571+
bytesDP = binr.ReadBytes(elems);
568572

569573
elems = GetIntegerSize(binr);
570-
DQ = binr.ReadBytes(elems);
574+
bytesDQ = binr.ReadBytes(elems);
571575

572576
elems = GetIntegerSize(binr);
573-
IQ = binr.ReadBytes(elems);
577+
bytesIQ = binr.ReadBytes(elems);
574578

575579
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
576580
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
577581
RSAParameters RSAparams = new RSAParameters();
578-
RSAparams.Modulus = MODULUS;
579-
RSAparams.Exponent = E;
580-
RSAparams.D = D;
581-
RSAparams.P = P;
582-
RSAparams.Q = Q;
583-
RSAparams.DP = DP;
584-
RSAparams.DQ = DQ;
585-
RSAparams.InverseQ = IQ;
582+
RSAparams.Modulus = bytesModulus;
583+
RSAparams.Exponent = bytesE;
584+
RSAparams.D = bytesD;
585+
RSAparams.P = bytesP;
586+
RSAparams.Q = bytesQ;
587+
RSAparams.DP = bytesDP;
588+
RSAparams.DQ = bytesDQ;
589+
RSAparams.InverseQ = bytesIQ;
586590
RSA.ImportParameters(RSAparams);
587591
return RSA;
588592
}
@@ -637,7 +641,7 @@ namespace {{packageName}}.Client
637641
private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter)
638642
{
639643
IntPtr unmanagedPswd = IntPtr.Zero;
640-
int HASHLENGTH = 16; //MD5 bytes
644+
const int HASHLENGTH = 16; //MD5 bytes
641645
byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results
642646
643647
byte[] psbytes = new byte[secpswd.Length];
@@ -670,7 +674,9 @@ namespace {{packageName}}.Client
670674
}
671675

672676
for (int i = 0; i < count; i++)
677+
{
673678
result = md5.ComputeHash(result);
679+
}
674680
Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial
675681
}
676682
byte[] deskey = new byte[24];
@@ -708,47 +714,45 @@ namespace {{packageName}}.Client
708714
/// Detect the key type from the pem file.
709715
/// </summary>
710716
/// <param name="keyFilePath">key file path in pem format</param>
711-
/// <returns></returns>
717+
/// <returns>Private Key Type</returns>
712718
private PrivateKeyType GetKeyType(string keyFilePath)
713719
{
714720
if (!File.Exists(keyFilePath))
715721
{
716722
throw new Exception("Key file path does not exist.");
717723
}
718724

719-
var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY";
720-
var ecPrivateKeyFooter = "END EC PRIVATE KEY";
721-
var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY";
722-
var rsaPrivateFooter = "END RSA PRIVATE KEY";
725+
const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY";
726+
const string ecPrivateKeyFooter = "END EC PRIVATE KEY";
727+
const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY";
728+
const string rsaPrivateFooter = "END RSA PRIVATE KEY";
723729
//var pkcs8Header = "BEGIN PRIVATE KEY";
724730
//var pkcs8Footer = "END PRIVATE KEY";
725-
var keyType = PrivateKeyType.None;
731+
PrivateKeyType keyType;
726732
var key = File.ReadAllLines(keyFilePath);
727733

728-
if (key[0].ToString().Contains(rsaPrivateKeyHeader) &&
734+
if (key[0].Contains(rsaPrivateKeyHeader) &&
729735
key[key.Length - 1].ToString().Contains(rsaPrivateFooter))
730736
{
731737
keyType = PrivateKeyType.RSA;
732738
}
733-
else if (key[0].ToString().Contains(ecPrivateKeyHeader) &&
739+
else if (key[0].Contains(ecPrivateKeyHeader) &&
734740
key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter))
735741
{
736742
keyType = PrivateKeyType.ECDSA;
737743
}
738-
else if (key[0].ToString().Contains(ecPrivateKeyHeader) &&
744+
else if (key[0].Contains(ecPrivateKeyHeader) &&
739745
key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter))
740746
{
741747
742-
/* this type of key can hold many type different types of private key, but here due lack of pem header
743-
Considering this as EC key
744-
*/
748+
// this type of key can hold many type different types of private key, but here due lack of pem header
749+
// Considering this as EC key
745750
//TODO :- update the key based on oid
746751
keyType = PrivateKeyType.ECDSA;
747752
}
748753
else
749754
{
750755
throw new Exception("Either the key is invalid or key is not supported");
751-
752756
}
753757
return keyType;
754758
}

0 commit comments

Comments
 (0)