/// <summary>CreateJwkFromDictionary</summary> /// <param name="dic">Dictionary</param> /// <param name="settings">JsonSerializerSettings</param> /// <returns>JwkString</returns> internal static string CreateJwkFromDictionary( Dictionary <string, string> dic, JsonSerializerSettings settings = null) { // JSON Web Key (JWK) Thumbprint // https://openid-foundation-japan.github.io/rfc7638.ja.html // kid : https://openid-foundation-japan.github.io/rfc7638.ja.html#Example // https://openid-foundation-japan.github.io/rfc7638.ja.html#MembersUsed // kidには、JWK の JWK Thumbprint 値などが用いられるらしい。 // ★ EC 公開鍵の必須メンバを辞書順に並べると、crv, kty, x, y となる。 dic[JwtConst.kid] = CustomEncode.ToBase64UrlString( GetHash.GetHashBytes( CustomEncode.StringToByte( JsonConvert.SerializeObject(new { crv = dic[JwtConst.crv], kty = dic[JwtConst.kty], x = dic[JwtConst.x], y = dic[JwtConst.y] }), CustomEncode.UTF_8), EnumHashAlgorithm.SHA256_M)); //dic["ext"] = "false"; // 定義をRFC上に発見できない。 if (settings == null) { return(JsonConvert.SerializeObject(dic)); } else { return(JsonConvert.SerializeObject(dic, settings)); } }
/// <summary>HSXXXのJWS生成メソッド</summary> /// <param name="payloadJson">ペイロード部のJson文字列</param> /// <returns>JWSの文字列表現</returns> public override string Create(string payloadJson) { // ヘッダー JWS_Header headerObject = new JWS_Header { alg = this.JwtConstHSnnn }; string headerJson = JsonConvert.SerializeObject( headerObject, new JsonSerializerSettings() { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore }); byte[] headerBytes = CustomEncode.StringToByte(headerJson, CustomEncode.UTF_8); string headerEncoded = CustomEncode.ToBase64UrlString(headerBytes); // ペイロード byte[] payloadBytes = CustomEncode.StringToByte(payloadJson, CustomEncode.UTF_8); string payloadEncoded = CustomEncode.ToBase64UrlString(payloadBytes); // 署名 byte[] data = CustomEncode.StringToByte(headerEncoded + "." + payloadEncoded, CustomEncode.UTF_8); HMAC sa = this.CreateHMACSHA(this.Key); string signEncoded = CustomEncode.ToBase64UrlString(sa.ComputeHash(data)); return(headerEncoded + "." + payloadEncoded + "." + signEncoded); }
/// <summary>ES256のJWS生成メソッド</summary> /// <param name="payloadJson">ペイロード部のJson文字列</param> /// <returns>JWSの文字列表現</returns> public override string Create(string payloadJson) { // ヘッダー string headerJson = JsonConvert.SerializeObject( this.JWSHeader, new JsonSerializerSettings() { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore }); byte[] headerBytes = CustomEncode.StringToByte(headerJson, CustomEncode.UTF_8); string headerEncoded = CustomEncode.ToBase64UrlString(headerBytes); // ペイロード byte[] payloadBytes = CustomEncode.StringToByte(payloadJson, CustomEncode.UTF_8); string payloadEncoded = CustomEncode.ToBase64UrlString(payloadBytes); // 署名 byte[] temp = CustomEncode.StringToByte(headerEncoded + "." + payloadEncoded, CustomEncode.UTF_8); string signEncoded = CustomEncode.ToBase64UrlString(this.Create2(temp)); // 派生を呼ぶ // return JWS by ES256 return(headerEncoded + "." + payloadEncoded + "." + signEncoded); }
/// <summary>文字列のハッシュ値を計算して返す。</summary> /// <param name="sourceString">文字列</param> /// <param name="eha">ハッシュ・アルゴリズム列挙型</param> /// <returns>ハッシュ値(文字列)</returns> public static string GetHashString(string sourceString, EnumHashAlgorithm eha) { // ハッシュ(Base64) return(CustomEncode.ToBase64String( GetHash.GetHashBytes( CustomEncode.StringToByte(sourceString, CustomEncode.UTF_8), eha))); }
/// <summary> /// code_challenge_method=S256 /// BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))</summary> /// <param name="code_verifier">string</param> /// <returns>code_challenge</returns> public static string PKCE_S256_CodeChallengeMethod(string code_verifier) { return(CustomEncode.ToBase64UrlString( GetHash.GetHashBytes( CustomEncode.StringToByte(code_verifier, CustomEncode.us_ascii), EnumHashAlgorithm.SHA256_M))); }
/// <summary>署名</summary> private void btnCCSign_Click(object sender, EventArgs e) { DigitalSignXML csXML = null; DigitalSignX509 csX509 = null; byte[] data = CustomEncode.StringToByte(this.txtCCData.Text, CustomEncode.UTF_8); byte[] sign = null; //bool ret = false; if (rbnCCXML.Checked) { // XMLKey csXML = new DigitalSignXML((EnumDigitalSignAlgorithm)this.cbxCCXMLPV.SelectedValue); sign = csXML.Sign(data); //ret = csXML.Verify(data, sign); txtCCPrivateKey.Text = csXML.XMLPrivateKey; txtCCPublicKey.Text = csXML.XMLPublicKey; } else { // X509Cer csX509 = new DigitalSignX509(this.CertificateFilePath_pfx, this.CertificateFilePassword, this.txtCCHash.Text); sign = csX509.Sign(data); //ret = csX509.Verify(data, sign); txtCCPrivateKey.Text = csX509.X509PrivateKey; txtCCPublicKey.Text = csX509.X509PublicKey; } txtCCSign.Text = CustomEncode.ToBase64String(sign); }
/// <summary> /// Tokenエンドポイントで、 /// Client Credentialsグラント種別の要求を行う。</summary> /// <param name="tokenEndpointUri">TokenエンドポイントのUri</param> /// <param name="client_id">string</param> /// <param name="client_secret">string</param> /// <param name="scopes">string</param> /// <returns>結果のJSON文字列</returns> public async Task <string> ClientCredentialsFlowAsync(Uri tokenEndpointUri, string client_id, string client_secret, string scopes) { // 通信用の変数 HttpRequestMessage httpRequestMessage = null; HttpResponseMessage httpResponseMessage = null; // HttpRequestMessage (Method & RequestUri) httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = tokenEndpointUri, }; // HttpRequestMessage (Headers & Content) httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue( "Basic", CustomEncode.ToBase64String(CustomEncode.StringToByte( string.Format("{0}:{1}", client_id, client_secret), CustomEncode.us_ascii))); httpRequestMessage.Content = new FormUrlEncodedContent( new Dictionary <string, string> { { "grant_type", ASPNETIdentityConst.ClientCredentialsGrantType }, { "scope", scopes }, }); // HttpResponseMessage httpResponseMessage = await _oAuthHttpClient.SendAsync(httpRequestMessage); return(await httpResponseMessage.Content.ReadAsStringAsync()); }
/// <summary>VerifyRedirect</summary> /// <param name="queryString">string</param> /// <param name="dsRSAwithSHA1">DigitalSign</param> /// <returns>bool</returns> public static bool VerifyRedirect(string queryString, DigitalSign dsRSAwithSHA1) { // EcodeRedirectの逆 // Signatureの抽出 string signature = StringExtractor.GetParameterFromQueryString("Signature", queryString); // Signatureの削除 queryString = queryString.Replace("&Signature=" + signature, ""); // queryString : ASCIIデコード // signature : パラメタ → URLデコード → Base64デコード if (dsRSAwithSHA1.Verify( CustomEncode.StringToByte(queryString, CustomEncode.us_ascii), CustomEncode.FromBase64String(CustomEncode.UrlDecode(signature)))) { // 署名検証 OK return(true); } else { // 署名検証 NG return(false); } }
/// <summary>Introspectエンドポイントで、Tokenを無効化する。</summary> /// <param name="introspectTokenEndpointUri">IntrospectエンドポイントのUri</param> /// <param name="client_id">client_id</param> /// <param name="client_secret">client_secret</param> /// <param name="token">token</param> /// <param name="token_type_hint">token_type_hint</param> /// <returns>結果のJSON文字列</returns> public async Task <string> IntrospectTokenAsync( Uri introspectTokenEndpointUri, string client_id, string client_secret, string token, string token_type_hint) { // 通信用の変数 HttpRequestMessage httpRequestMessage = null; HttpResponseMessage httpResponseMessage = null; // HttpRequestMessage (Method & RequestUri) httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = introspectTokenEndpointUri, }; // HttpRequestMessage (Headers & Content) httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue( "Basic", CustomEncode.ToBase64String(CustomEncode.StringToByte( string.Format("{0}:{1}", client_id, client_secret), CustomEncode.us_ascii))); httpRequestMessage.Content = new FormUrlEncodedContent( new Dictionary <string, string> { { "token", token }, { "token_type_hint", token_type_hint }, }); // HttpResponseMessage httpResponseMessage = await _oAuthHttpClient.SendAsync(httpRequestMessage); return(await httpResponseMessage.Content.ReadAsStringAsync()); }
/// <summary> /// Password entered by the userをDB保存する際、 /// Salted and hashed passwordとして保存する必要がある。 /// </summary> /// <param name="rawPassword">Password entered by the user.</param> /// <param name="ekha">ハッシュ・アルゴリズム列挙型</param> /// <param name="key">キー</param> /// <param name="saltLength">ソルトの文字列長</param> /// <param name="stretchCount">ストレッチ回数</param> /// <returns>Salted and hashed password.</returns> public static string GetSaltedPassword(string rawPassword, EnumKeyedHashAlgorithm ekha, string key, int saltLength, int stretchCount) { // ランダム・ソルト文字列を生成(区切り記号は含まなくても良い) string salt = GetPassword.Generate(saltLength, 0); //Membership.GeneratePassword(saltLength, 0); byte[] saltByte = CustomEncode.StringToByte(salt, CustomEncode.UTF_8); // KeyedHashのキーを生成する。 Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes(key, saltByte, stretchCount); // Salted and hashed password(文字列)を生成して返す。 return // key (CustomEncode.ToBase64String(CustomEncode.StringToByte(key, CustomEncode.UTF_8)) // saltByte + "." + CustomEncode.ToBase64String(saltByte) // stretchCount + "." + CustomEncode.ToBase64String(CustomEncode.StringToByte(stretchCount.ToString(), CustomEncode.UTF_8)) // Salted and hashed password + "." + CustomEncode.ToBase64String( GetPasswordHashV2.GetKeyedHashBytes( CustomEncode.StringToByte(salt + rawPassword, CustomEncode.UTF_8), ekha, passwordKey.GetBytes(24)))); }
/// <summary>constructor</summary> /// <param name="json">string</param> public JsonContent(string json) { Headers.ContentType = new MediaTypeHeaderValue("application/json"); this._Stream = new MemoryStream(CustomEncode.StringToByte(json, CustomEncode.UTF_8)); this._Stream.Position = 0; }
/// <summary>MAC値を検証</summary> /// <param name="msg">メッセージ(文字列)</param> /// <param name="ekha">MACアルゴリズム列挙型</param> /// <param name="key">キー(文字列)</param> /// <param name="mac">MAC値(base64文字列)</param> /// <returns>検証結果( true:検証成功, false:検証失敗 )</returns> public static bool VerifyMAC(string msg, EnumKeyedHashAlgorithm ekha, string key, string mac) { return(MsgAuthCode.VerifyMAC( CustomEncode.StringToByte(msg, CustomEncode.UTF_8), ekha, CustomEncode.StringToByte(key, CustomEncode.UTF_8), CustomEncode.FromBase64String(mac))); }
/// <summary>文字列を暗号化する</summary> /// <param name="sourceString">暗号化する文字列</param> /// <param name="password">暗号化に使用するパスワード</param> /// <returns>暗号化された文字列</returns> public string EncryptString(string sourceString, string password) { // 元文字列をbyte型配列に変換する(UTF-8 Enc) byte[] source = CustomEncode.StringToByte(sourceString, CustomEncode.UTF_8); // 暗号化(Base64) return(CustomEncode.ToBase64String(this.EncryptBytes(source, password))); }
/// <summary>文字列のハッシュ値を計算して返す。</summary> /// <param name="ss">文字列</param> /// <param name="ekha">ハッシュ(キー付き)アルゴリズム列挙型</param> /// <param name="password">使用するパスワード</param> /// <param name="salt">ソルト</param> /// <param name="stretching">ストレッチング</param> /// <returns>ハッシュ値(文字列)</returns> public static string GetKeyedHashString(string ss, EnumKeyedHashAlgorithm ekha, string password, byte[] salt, int stretching) { // ハッシュ(Base64) return(CustomEncode.ToBase64String( GetKeyedHashBytes( CustomEncode.StringToByte(ss, CustomEncode.UTF_8), ekha, password, salt, stretching))); }
/// <summary>検証</summary> private void btnDSVerify_Click(object sender, EventArgs e) { DigitalSignXML dsXML = null; DigitalSignParam dsParam = null; DigitalSignX509 dsX509 = null; byte[] data = CustomEncode.StringToByte(this.txtDSData.Text, CustomEncode.UTF_8); byte[] sign = CustomEncode.FromBase64String(this.txtDSSign.Text); bool ret = false; if (rbnDSXML.Checked) { // XMLKey dsXML = new DigitalSignXML( (EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue, this.txtDSPublicKey.Text); ret = dsXML.Verify(data, sign); } else if (rbnDSParam.Checked) { // XMLKey dsXML = new DigitalSignXML( (EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue, this.txtDSPublicKey.Text); if (((EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue) == EnumDigitalSignAlgorithm.DSACryptoServiceProvider_SHA1) { DSAParameters dsaparam = ((DSACryptoServiceProvider)dsXML.AsymmetricAlgorithm).ExportParameters(false); dsParam = new DigitalSignParam(dsaparam, dsXML.HashAlgorithm); } else { RSAParameters rsaparam = ((RSACryptoServiceProvider)dsXML.AsymmetricAlgorithm).ExportParameters(false); dsParam = new DigitalSignParam(rsaparam, dsXML.HashAlgorithm); } ret = dsXML.Verify(data, sign); } else { // X509 //// *.pfxを使用して、検証することもできるが、 //dsX509 = new DigitalSignX509(this.CertificateFilePath_pfx, this.CertificateFilePassword, this.txtCCHash.Text, // X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); // 通常は、*.cerを使用して検証する。 dsX509 = new DigitalSignX509(CertificateFilePath_cer, "", this.txtDSHash.Text); ret = dsX509.Verify(data, sign); } if (ret) { MessageBox.Show("検証成功"); } else { MessageBox.Show("検証失敗"); } }
/// <summary>署名</summary> private void btnDSSign_Click(object sender, EventArgs e) { DigitalSignXML dsXML = null; DigitalSignParam dsParam = null; DigitalSignX509 dsX509 = null; byte[] data = CustomEncode.StringToByte(this.txtDSData.Text, CustomEncode.UTF_8); byte[] sign = null; if (rbnDSXML.Checked) { // XMLKey dsXML = new DigitalSignXML((EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue); sign = dsXML.Sign(data); //bool ret = csXML.Verify(data, sign); this.txtDSPrivateKey.Text = dsXML.XMLPrivateKey; this.txtDSPublicKey.Text = dsXML.XMLPublicKey; } else if (rbnDSParam.Checked) { // XMLKey dsXML = new DigitalSignXML((EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue); if (((EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue) == EnumDigitalSignAlgorithm.DSACryptoServiceProvider_SHA1) { DSAParameters dsaparam = ((DSACryptoServiceProvider)dsXML.AsymmetricAlgorithm).ExportParameters(true); dsParam = new DigitalSignParam(dsaparam, dsXML.HashAlgorithm); } else { RSAParameters rsaparam = ((RSACryptoServiceProvider)dsXML.AsymmetricAlgorithm).ExportParameters(true); dsParam = new DigitalSignParam(rsaparam, dsXML.HashAlgorithm); } sign = dsParam.Sign(data); //bool ret = dsParam.Verify(data, sign); this.txtDSPrivateKey.Text = dsXML.XMLPrivateKey; this.txtDSPublicKey.Text = dsXML.XMLPublicKey; } else { // X509 dsX509 = new DigitalSignX509(this.CertificateFilePath_pfx, this.CertificateFilePassword, this.txtDSHash.Text, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); sign = dsX509.Sign(data); //bool ret = dsX509.Verify(data, sign); this.txtDSPrivateKey.Text = dsX509.X509PrivateKey; this.txtDSPublicKey.Text = dsX509.X509PublicKey; } txtDSSign.Text = CustomEncode.ToBase64String(sign); }
/// <summary>文字列を暗号化する</summary> /// <param name="sourceString">暗号化する文字列</param> /// <param name="publicXmlKey">暗号化に使用する公開鍵</param> /// <param name="fOAEP"> /// ・true : OAEPパディング(XP以降) /// ・false : PKCS#1 v1.5パディング /// </param> /// <returns>非対称アルゴリズムで暗号化された文字列</returns> public string EncryptString(string sourceString, string publicXmlKey = "", bool fOAEP = false) { // 元文字列をbyte型配列に変換する(UTF-8 Enc) byte[] source = CustomEncode.StringToByte(sourceString, CustomEncode.UTF_8); // 暗号化(Base64) return(CustomEncode.ToBase64String( this.EncryptBytes(source, publicXmlKey, fOAEP))); }
/// <summary>文字列を暗号化する</summary> /// <param name="sourceString">暗号化する文字列</param> /// <param name="publicKey">暗号化に使用する公開鍵</param> /// <returns>非対称アルゴリズムで暗号化された文字列</returns> public static string EncryptString(string sourceString, string publicKey) { // 元文字列をbyte型配列に変換する(UTF-8 Enc) byte[] source = CustomEncode.StringToByte(sourceString, CustomEncode.UTF_8); // 暗号化(Base64) return(CustomEncode.ToBase64String( ASymmetricCryptography.EncryptBytes(source, publicKey))); }
/// <summary>文字列を暗号化する</summary> /// <param name="sourceString">暗号化する文字列</param> /// <param name="publicXmlKey">暗号化に使用する公開鍵</param> /// <param name="padding">RSAEncryptionPadding</param> /// <returns>非対称アルゴリズムで暗号化された文字列</returns> public string EncryptString(string sourceString, string publicXmlKey = "", RSAEncryptionPadding padding = null) { // 元文字列をbyte型配列に変換する(UTF-8 Enc) byte[] source = CustomEncode.StringToByte(sourceString, CustomEncode.UTF_8); // 暗号化(Base64) return(CustomEncode.ToBase64String( this.EncryptBytes(source, publicXmlKey, padding))); }
/// <summary> /// SHA256でat_hash, c_hashを作成。 /// (現時点でRS256固定になっているので) /// </summary> /// <returns>hash</returns> public static string CreateHash(string input) { // ID Token の JOSE Header にある alg Header Parameterのアルゴリズムで使用されるハッシュアルゴリズムを用い、 // input(access_token や code) のASCII オクテット列からハッシュ値を求め、左半分を base64url エンコードした値。 return(CustomEncode.ToBase64UrlString( PubCmnFunction.ShortenByteArray( GetHash.GetHashBytes( CustomEncode.StringToByte(input, CustomEncode.us_ascii), EnumHashAlgorithm.SHA256Managed), (256 / 2)))); }
/// <summary>文字列を暗号化する</summary> /// <param name="sourceString">暗号化する文字列</param> /// <param name="password">暗号化に使用するパスワード</param> /// <param name="esa"> /// 対称アルゴリズムによる /// 暗号化サービスプロバイダの種類 /// </param> /// <param name="salt">ソルト</param> /// <param name="stretching">ストレッチング</param> /// <returns> /// 対称アルゴリズムで /// 暗号化された文字列 /// </returns> public static string EncryptString( string sourceString, string password, EnumSymmetricAlgorithm esa, byte[] salt, int stretching) { // 元文字列をbyte型配列に変換する(UTF-8 Enc) byte[] source = CustomEncode.StringToByte(sourceString, CustomEncode.UTF_8); // 暗号化(Base64) return(CustomEncode.ToBase64String( SymmetricCryptography.EncryptBytes(source, password, esa, salt, stretching))); }
/// <summary> /// Password entered by the userをDB保存する際、 /// Salted and hashed passwordとして保存する必要がある。 /// </summary> /// <param name="rawPassword">>Password entered by the user.</param> /// <param name="eha">ハッシュ・アルゴリズム列挙型</param> /// <param name="saltLength">ソルトの文字列長</param> /// <param name="stretchCount">ストレッチ回数</param> /// <returns>Salted and hashed password.</returns> public static string GetSaltedPassword(string rawPassword, EnumHashAlgorithm eha, int saltLength, int stretchCount) { // ランダム・ソルト文字列を生成(区切り記号は含まなくても良い) string salt = GetPassword.Generate(saltLength, 0); //Membership.GeneratePassword(saltLength, 0); // Salted and hashed password(文字列)を生成して返す。 return (CustomEncode.ToBase64String(CustomEncode.StringToByte(salt, CustomEncode.UTF_8)) + "." + CustomEncode.ToBase64String(CustomEncode.StringToByte(stretchCount.ToString(), CustomEncode.UTF_8)) + "." + CustomEncode.ToBase64String(CustomEncode.StringToByte(GetHash.GetHashString(salt + rawPassword, eha, stretchCount), CustomEncode.UTF_8))); }
/// <summary>JWE復号メソッド</summary> /// <param name="jwtString">JWEの文字列表現</param> /// <param name="payloadJson">ペイロード部のJson文字列</param> /// <returns>復号の結果</returns> public bool Decrypt(string jwtString, out string payloadJson) { try { string[] temp = jwtString.Split('.'); // 検証 JWE_Header headerObject = (JWE_Header)JsonConvert.DeserializeObject( CustomEncode.ByteToString(CustomEncode.FromBase64UrlString(temp[0]), CustomEncode.UTF_8), typeof(JWE_Header)); if (headerObject.alg.ToUpper() == JWEHeader.alg.ToUpper() && headerObject.enc.ToUpper() == JWEHeader.enc.ToUpper() && headerObject.typ.ToUpper() == JWEHeader.typ.ToUpper()) { // コンテンツ暗号化キー(CEK) byte[] encryptedCekBytes = CustomEncode.FromBase64UrlString(temp[1]); byte[] cekBytes = this.DecryptKey(encryptedCekBytes); // 派生を呼ぶ // 初期化ベクトル byte[] ivBytes = CustomEncode.FromBase64UrlString(temp[2]); // 追加認証データ(AAD) byte[] aadBytes = CustomEncode.StringToByte(temp[0], CustomEncode.us_ascii); // ペイロード(認証付き暗号(AEAD)による暗号化) byte[] encryptedPayloadBytes = CustomEncode.FromBase64UrlString(temp[3]); // 認証タグ(MAC) byte[] macBytes = CustomEncode.FromBase64UrlString(temp[4]); // 復号化 byte[] payloadBytes = this.DecryptBody( // 派生を呼ぶ cekBytes, ivBytes, aadBytes, new AeadResult() { Ciphert = encryptedPayloadBytes, Tag = macBytes }); payloadJson = CustomEncode.ByteToString(payloadBytes, CustomEncode.UTF_8); return(true); } else { payloadJson = ""; return(false); } } catch { payloadJson = ""; return(false); } }
/// <summary>仲介コードからAccess Tokenを取得する。</summary> /// <param name="tokenEndpointUri">TokenエンドポイントのUri</param> /// <param name="client_id">client_id</param> /// <param name="client_secret">client_secret</param> /// <param name="redirect_uri">redirect_uri</param> /// <param name="code">code</param> /// <param name="code_verifier">code_verifier</param> /// <returns>結果のJSON文字列</returns> public async Task <string> GetAccessTokenByCodeAsync( Uri tokenEndpointUri, string client_id, string client_secret, string redirect_uri, string code, string code_verifier) { // 4.1.3. アクセストークンリクエスト // http://openid-foundation-japan.github.io/rfc6749.ja.html#token-req // 通信用の変数 HttpRequestMessage httpRequestMessage = null; HttpResponseMessage httpResponseMessage = null; // HttpRequestMessage (Method & RequestUri) httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = tokenEndpointUri, }; // HttpRequestMessage (Headers & Content) httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue( "Basic", CustomEncode.ToBase64String(CustomEncode.StringToByte( string.Format("{0}:{1}", client_id, client_secret), CustomEncode.us_ascii))); if (string.IsNullOrEmpty(code_verifier)) { // 通常のアクセストークン・リクエスト httpRequestMessage.Content = new FormUrlEncodedContent( new Dictionary <string, string> { { "grant_type", ASPNETIdentityConst.AuthorizationCodeGrantType }, { "code", code }, { "redirect_uri", HttpUtility.HtmlEncode(redirect_uri) }, }); } else { // OAuth PKCEのアクセストークン・リクエスト httpRequestMessage.Content = new FormUrlEncodedContent( new Dictionary <string, string> { { "grant_type", ASPNETIdentityConst.AuthorizationCodeGrantType }, { "code", code }, { "code_verifier", code_verifier }, { "redirect_uri", HttpUtility.HtmlEncode(redirect_uri) }, }); } // HttpResponseMessage httpResponseMessage = await _oAuthHttpClient.SendAsync(httpRequestMessage); return(await httpResponseMessage.Content.ReadAsStringAsync()); }
/// <summary> /// at_hash, c_hash, s_hashを作成 /// (SHA256→HS256,RS256,ES256対応可能) /// </summary> /// <param name="input">string</param> /// <returns>hash</returns> public static string CreateHash(string input) { // ID Token の JOSE Header にある // alg Header Parameterのアルゴリズムで使用されるハッシュアルゴリズムを用い、 // input(access_token や code) のASCII オクテット列からハッシュ値を求め、 byte[] bytes = GetHash.GetHashBytes( CustomEncode.StringToByte(input, CustomEncode.us_ascii), EnumHashAlgorithm.SHA256_M); // 左半分を base64url エンコードした値。 return(CustomEncode.ToBase64UrlString( ArrayOperator.ShortenByteArray(bytes, (bytes.Length / 2)))); }
/// <summary>ハッシュ</summary> private void btnGetHash_Click(object sender, EventArgs e) { if (this.rbnHSString.Checked) { txtHSCode.Text = GetHash.GetHashString( txtHSString.Text, (EnumHashAlgorithm)cbxHSPV.SelectedValue); } else { txtHSCode.Text = CustomEncode.ToHexString(GetHash.GetHashBytes( CustomEncode.StringToByte(txtHSString.Text, CustomEncode.UTF_8), (EnumHashAlgorithm)cbxHSPV.SelectedValue)); } }
/// <summary>ChargeToOnlinePaymentCustomersAsync</summary> /// <param name="customerId">customerId</param> /// <param name="currency">currency(jpy, etc.)</param> /// <param name="amount">amount</param> /// <returns>JObject</returns> public async Task <JObject> ChargeToOnlinePaymentCustomersAsync(string customerId, string currency, string amount) { // URL string secretKey = ""; Uri webApiEndpointUri = null; if (ASPNETIdentityConfig.EnableStripe) { webApiEndpointUri = new Uri("https://api.stripe.com/v1/charges"); secretKey = ASPNETIdentityConfig.Stripe_SK; } else if (ASPNETIdentityConfig.EnablePAYJP) { webApiEndpointUri = new Uri("https://api.pay.jp/v1/charges"); secretKey = ASPNETIdentityConfig.PAYJP_SK + ":"; // 「:」はUID:PWDの「:」 } else { throw new NotSupportedException("Payment service is not enabled."); } // 通信用の変数 HttpRequestMessage httpRequestMessage = null; HttpResponseMessage httpResponseMessage = null; // HttpRequestMessage (Method & RequestUri) httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = webApiEndpointUri }; // HttpRequestMessage (Headers) httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue( OAuth2AndOIDCConst.Basic, CustomEncode.ToBase64String(CustomEncode.StringToByte(secretKey, CustomEncode.us_ascii))); httpRequestMessage.Content = new FormUrlEncodedContent( new Dictionary <string, string> { { "amount", amount }, { "currency", currency }, { "customer", customerId } }); httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); // HttpResponseMessage httpResponseMessage = await _webAPIHttpClient.SendAsync(httpRequestMessage); return((JObject)JsonConvert.DeserializeObject(await httpResponseMessage.Content.ReadAsStringAsync())); }
/// <summary>CreateBasicAuthenticationHeaderValue</summary> /// <param name="id">string</param> /// <param name="secret">string</param> /// <returns>AuthenticationHeaderValue</returns> public static AuthenticationHeaderValue CreateBasicAuthenticationHeaderValue(string id, string secret) { // id + x509 のパターンをサポート if (!string.IsNullOrEmpty(id)) // && !string.IsNullOrEmpty(secret)) { return(new AuthenticationHeaderValue( OAuth2AndOIDCConst.Basic, CustomEncode.ToBase64String(CustomEncode.StringToByte( string.Format("{0}:{1}", id, secret), CustomEncode.us_ascii)))); } else { return(null); } }
/// <summary>MemoryStream</summary> private static void MemoryStream() { // DeflateCompression byte[] input = CustomEncode.StringToByte(TestDeflateCompression.hoge, CustomEncode.UTF_8); byte[] compressed = DeflateCompression.Compress(input); byte[] decompressed = DeflateCompression.Decompress(compressed); if (TestDeflateCompression.hoge == CustomEncode.ByteToString(decompressed, CustomEncode.UTF_8)) { MyDebug.OutputDebugAndConsole("DeflateCompression(MemoryStream)", "is working properly."); } else { MyDebug.OutputDebugAndConsole("DeflateCompression(MemoryStream)", "is not working properly."); } }
/// <summary>JWT検証</summary> private void btnJWTVerify_Click(object sender, EventArgs e) { bool ret = false; if (rbnJWTHS256.Checked) { // HS256 // 入力 string[] temp = this.txtJWTSign.Text.Split('.'); // 改変可能なフィールドから入力 string newJWT = CustomEncode.ToBase64UrlString(CustomEncode.StringToByte(this.txtJWTHeader.Text, CustomEncode.UTF_8)) + "." + CustomEncode.ToBase64UrlString(CustomEncode.StringToByte(this.txtJWTPayload.Text, CustomEncode.UTF_8)) + "." + temp[2]; // 検証 JWT_HS256 jwtHS256 = new JWT_HS256(CustomEncode.StringToByte(this.txtJWTKey.Text, CustomEncode.UTF_8)); ret = jwtHS256.Verify(newJWT); } else { // RS256 (X509Cer) // 入力 string[] temp = this.txtJWTSign.Text.Split('.'); // 改変可能なフィールドから入力 string newJWT = CustomEncode.ToBase64UrlString(CustomEncode.StringToByte(this.txtJWTHeader.Text, CustomEncode.UTF_8)) + "." + CustomEncode.ToBase64UrlString(CustomEncode.StringToByte(this.txtJWTPayload.Text, CustomEncode.UTF_8)) + "." + temp[2]; // 検証 JWT_RS256 jwtRS256 = new JWT_RS256(this.CertificateFilePath_cer, ""); ret = jwtRS256.Verify(newJWT); } if (ret) { MessageBox.Show("検証成功"); } else { MessageBox.Show("検証失敗"); } }