/// <summary> /// Converts a base-58 string to a byte array, returning null if it wasn't valid. /// </summary> public static byte[] ToByteArray(string base58) { Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0"); string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; foreach (char c in base58) { if (b58.IndexOf(c) != -1) { bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58")); bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString())); } else { return(null); } } byte[] bb = bi2.ToByteArrayUnsigned(); // interpret leading '1's as leading zero bytes foreach (char c in base58) { if (c != '1') { break; } byte[] bbb = new byte[bb.Length + 1]; Array.Copy(bb, 0, bbb, 1, bb.Length); bb = bbb; } return(bb); }
/// <summary> /// Converts a base-58 string to a byte array, returning null if it wasn't valid. /// </summary> public static byte[] ToByteArray(string base58) { Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0"); string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; foreach (char c in base58) { if (b58.IndexOf(c) != -1) { bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58")); bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString())); } else { return null; } } byte[] bb = bi2.ToByteArrayUnsigned(); // interpret leading '1's as leading zero bytes foreach (char c in base58) { if (c != '1') break; byte[] bbb = new byte[bb.Length + 1]; Array.Copy(bb, 0, bbb, 1, bb.Length); bb = bbb; } return bb; }
public static byte[] FromBase58String(string base58) { Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0"); foreach (char c in base58) { if (b58.IndexOf(c) != -1) { bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58")); bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString())); } else { return(null); } } byte[] bb = bi2.ToByteArrayUnsigned(); // interpret leading '1's as leading zero bytes foreach (char c in base58) { if (c != leadingZeroCharacter[0]) { break; } byte[] bbb = new byte[bb.Length + 1]; Array.Copy(bb, 0, bbb, 1, bb.Length); bb = bbb; } return(bb); }
static byte[] ConvertRSAParametersField(Org.BouncyCastle.Math.BigInteger n, int size) { byte[] bs = n.ToByteArrayUnsigned(); if (bs.Length == size) return bs; if (bs.Length > size) throw new ArgumentException("Specified size too small", "size"); byte[] padded = new byte[size]; Array.Copy(bs, 0, padded, size - bs.Length, bs.Length); return padded; }
public static byte[] Base58ToByteArray(string base58) { Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0"); string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool IgnoreChecksum = false; foreach (char c in base58) { if (b58.IndexOf(c) != -1) { bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58")); bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString())); } else if (c == '?') { IgnoreChecksum = true; } else { return null; } } byte[] bb = bi2.ToByteArrayUnsigned(); // interpret leading '1's as leading zero bytes foreach (char c in base58) { if (c != '1') break; byte[] bbb = new byte[bb.Length + 1]; Array.Copy(bb, 0, bbb, 1, bb.Length); bb = bbb; } if (bb.Length < 4) return null; if (IgnoreChecksum == false) { SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider(); byte[] checksum = sha256.ComputeHash(bb, 0, bb.Length - 4); checksum = sha256.ComputeHash(checksum); for (int i = 0; i < 4; i++) { if (checksum[i] != bb[bb.Length - 4 + i]) return null; } } byte[] rv = new byte[bb.Length - 4]; Array.Copy(bb, 0, rv, 0, bb.Length - 4); return rv; }
public static ECDsa LoadPrivateKey(byte[] key) { var privKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, key); var parameters = SecNamedCurves.GetByName("secp256r1"); var ecPoint = parameters.G.Multiply(privKeyInt); var privKeyX = ecPoint.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned(); var privKeyY = ecPoint.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned(); return(ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, D = privKeyInt.ToByteArrayUnsigned(), Q = new ECPoint { X = privKeyX, Y = privKeyY } })); }
private byte[] Base58ToByteArray(string base58) { Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0"); string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool IgnoreChecksum = false; foreach (char c in base58) { if (b58.IndexOf(c) != -1) { bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58")); bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString())); } else if (c == '?') { IgnoreChecksum = true; } else { return(null); } } byte[] bb = bi2.ToByteArrayUnsigned(); // interpret leading '1's as leading zero bytes foreach (char c in base58) { if (c != '1') { break; } byte[] bbb = new byte[bb.Length + 1]; System.Array.Copy(bb, 0, bbb, 1, bb.Length); bb = bbb; } if (bb.Length < 4) { return(null); } if (IgnoreChecksum == false) { ////////////////////////////////////SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider(); SHA256 sha256 = SHA256.Create(); // SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider(); byte[] checksum = sha256.ComputeHash(bb, 0, bb.Length - 4); checksum = sha256.ComputeHash(checksum); for (int i = 0; i < 4; i++) { if (checksum[i] != bb[bb.Length - 4 + i]) { return(null); } } } byte[] rv = new byte[bb.Length - 4]; System.Array.Copy(bb, 0, rv, 0, bb.Length - 4); return(rv); }
public static BigInteger ToNumericsBigInteger(this Org.BouncyCastle.Math.BigInteger bcBigInteger) { return(BigIntegerConverter.GetBigInteger(bcBigInteger.ToByteArrayUnsigned())); }
public static string ToHexNumberStringUnsigned(this BigIntegerBouncy value) { return(value.ToByteArrayUnsigned().Reverse().ToHexNumberString()); }
public async Task <IActionResult> Login([FromBody] LoginModel model) { if (string.IsNullOrWhiteSpace(model?.AuthCode)) { return(BadRequest()); } // CREATING THE JWT // your private signing key from Civic const string privateKey = "e8593ad98db1dda0f57c16ef1f53c4c6b57fa35d9b5f82602353ccfb5a71f047"; var privKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, FromHexString(privateKey)); var parameters = SecNamedCurves.GetByName("secp256r1"); var qa = parameters.G.Multiply(privKeyInt); var privKeyX = qa.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned(); var privKeyY = qa.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned(); var privateKeyEcdsa = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, D = privKeyInt.ToByteArrayUnsigned(), Q = new ECPoint { X = privKeyX, Y = privKeyY } }); var now = DateTime.UtcNow; var tokenHandler = new JwtSecurityTokenHandler(); var signingCredentials = new SigningCredentials(new ECDsaSecurityKey(privateKeyEcdsa), SecurityAlgorithms.EcdsaSha256); var jwtHeader = new JwtHeader(signingCredentials); var jwtPayload = new JwtPayload( issuer: "rJ3fVI9rz", audience: "https://api.civic.com/sip", claims: new List <Claim> { new Claim("sub", "rJ3fVI9rz"), new Claim("jti", Guid.NewGuid().ToString()) }, notBefore: null, expires: now.AddMinutes(5), issuedAt: now); jwtPayload.Add("data", new Dictionary <string, string> { { "method", "POST" }, { "path", "scopeRequest/authCode" } }); var exchangeToken = tokenHandler.WriteToken(new JwtSecurityToken(jwtHeader, jwtPayload)); // CREATING THE MESSAGE DIGEST // your secret from Civic const string secret = "482283244e2e8082d6f1c3ef288930ce"; var data = JsonConvert.SerializeObject(new { authToken = model.AuthCode }); var secretBytes = Encoding.Default.GetBytes(secret); var dataBytes = Encoding.Default.GetBytes(data); var hmac = new HMACSHA256(secretBytes); var hashAsBytes = hmac.ComputeHash(dataBytes); var hash = Convert.ToBase64String(hashAsBytes); // REQUESTING USER DATA var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Civic", $"{exchangeToken}.{hash}"); var responseMessage = await httpClient.PostAsync("https://api.civic.com/sip/prod/scopeRequest/authCode", new StringContent(data, Encoding.UTF8, "application/json")); var response = await responseMessage.Content.ReadAsStringAsync(); // VERIFYING THE JWT SIGNATURE const string civicAuthServerPublicKey = "049a45998638cfb3c4b211d72030d9ae8329a242db63bfb0076a54e7647370a8ac5708b57af6065805d5a6be72332620932dbb35e8d318fce18e7c980a0eb26aa1"; var pubKeyX = FromHexString(civicAuthServerPublicKey).Skip(1).Take(32).ToArray(); var pubKeyY = FromHexString(civicAuthServerPublicKey).Skip(33).ToArray(); var publicKeyEcdsa = ECDsa.Create(new ECParameters { Curve = ECCurve.CreateFromFriendlyName("secp256r1"), Q = new ECPoint { X = pubKeyX, Y = pubKeyY } }); var jObject = JObject.Parse(response); var jToken = jObject["data"]; var jwt = jToken.Value <string>(); var claimsPrincipal = tokenHandler.ValidateToken(jwt, new TokenValidationParameters { ValidIssuer = "civic-sip-hosted-service", ValidateIssuer = true, ValidAudience = "https://api.civic.com/sip/", ValidateAudience = true, ValidateLifetime = true, IssuerSigningKey = new ECDsaSecurityKey(publicKeyEcdsa) }, out var _); // DECRYPTING THE DATA var loadedData = claimsPrincipal.FindFirst("data").Value; var iv = FromHexString(loadedData.Substring(0, 32)); var encryptedData = Convert.FromBase64String(loadedData.Substring(32)); string plainTextUserData; var aes = Aes.Create(); aes.IV = iv; aes.Key = FromHexString(secret); using (aes) using (var memoryStream = new MemoryStream(encryptedData)) using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Read)) using (var srDecrypt = new StreamReader(cryptoStream)) plainTextUserData = srDecrypt.ReadToEnd(); var userData = JsonConvert.DeserializeObject <List <UserData> >(plainTextUserData); // AUTHENTICATING THE USER var claimsIdentity = new ClaimsIdentity(userData.Select(x => new Claim(x.Label, x.Value)).ToList(), "cookie"); claimsIdentity.AddClaim(new Claim("userId", jObject["userId"].Value <string>())); await HttpContext.SignInAsync("cookie", new ClaimsPrincipal(claimsIdentity)); return(Ok()); }