/// <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> /// 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>署名</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> /// Inserts data to database /// </summary> /// <returns></returns> public AsyncProcessingServiceParameterValue InsertData() { AsyncProcessingServiceParameterValue asyncParameterValue; byte[] arr = { 1, 2, 3, 4, 5 }; asyncParameterValue = new AsyncProcessingServiceParameterValue("AsyncProcessingService", "Start", "Start", "SQL", new MyUserInfo("AsyncProcessingService", "AsyncProcessingService")); asyncParameterValue.UserId = "A"; asyncParameterValue.ProcessName = "AAA"; asyncParameterValue.Data = CustomEncode.ToBase64String(arr); asyncParameterValue.ExecutionStartDateTime = DateTime.Now; asyncParameterValue.RegistrationDateTime = DateTime.Now; asyncParameterValue.NumberOfRetries = 0; asyncParameterValue.ProgressRate = 0; asyncParameterValue.CompletionDateTime = DateTime.Now; asyncParameterValue.StatusId = (int)(AsyncProcessingServiceParameterValue.AsyncStatus.Register); asyncParameterValue.CommandId = 0; asyncParameterValue.ReservedArea = "xxxxxx"; DbEnum.IsolationLevelEnum iso = DbEnum.IsolationLevelEnum.DefaultTransaction; AsyncProcessingServiceReturnValue asyncReturnValue; AsyncSvc_sample.LayerB layerB = new AsyncSvc_sample.LayerB(); asyncReturnValue = (AsyncProcessingServiceReturnValue)layerB.DoBusinessLogic((AsyncProcessingServiceParameterValue)asyncParameterValue, iso); return(asyncParameterValue); }
/// <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>文字列のハッシュ値を計算して返す。</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>MAC値を検証</summary> /// <param name="msg">メッセージ(バイト配列)</param> /// <param name="ekha">MACアルゴリズム列挙型</param> /// <param name="key">キー(バイト配列)</param> /// <param name="mac">MAC値(バイト配列)</param> /// <returns>検証結果( true:検証成功, false:検証失敗 )</returns> public static bool VerifyMAC(byte[] msg, EnumKeyedHashAlgorithm ekha, byte[] key, byte[] mac) { // 文字列にしてから計算 string paramMac = CustomEncode.ToBase64String(mac); string calcMac = CustomEncode.ToBase64String(MsgAuthCode.GetMAC(msg, ekha, key)); return(paramMac == calcMac); }
/// <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>GetBase64StringFromPemFilePath</summary> /// <param name="pemFilePath">string</param> /// <param name="label">RFC7468Label</param> /// <returns>Base64String</returns> public static string GetBase64StringFromPemFilePath(string pemFilePath, RFC7468Label label) { string pemString = File.ReadAllText(pemFilePath); return(CustomEncode.ToBase64String( PrivacyEnhancedMail.GetBytesFromPemString( pemString, PrivacyEnhancedMail.EnumToString(label)))); }
/// <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>文字列を暗号化する</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> /// Converts byte array to serialized base64 string /// </summary> /// <param name="arrayData">byte array</param> /// <returns>base64 string</returns> public static string SerializeToBase64String(byte[] arrayData) { string base64String = string.Empty; if (arrayData != null) { CustomEncode.ToBase64String(arrayData); } return(base64String); }
/// <summary>Main</summary> /// <param name="args">string[]</param> static void Main(string[] args) { string ver = ""; #if NET45 ver = "NET45"; #elif NET46 ver = "NET46"; #elif NET47 ver = "NET47"; #elif NET48 ver = "NET48"; #elif NETCORE20 ver = "NETCORE20"; #elif NETCORE30 ver = "NETCORE30"; #else #endif string filePath = ""; string fileName = "TestBinarySerializeXplat.txt"; if (System.Environment.OSVersion.Platform == PlatformID.Win32NT) { filePath = @"C:\Users\nishi\"; } else { filePath = "/mnt/c/Users/nishi/"; } filePath += fileName; Dictionary <string, string> dic = null; if (File.Exists(filePath)) { dic = (Dictionary <string, string>) BinarySerialize.BytesToObject( CustomEncode.FromBase64String( ResourceLoader.LoadAsString(filePath, Encoding.UTF8))); Console.WriteLine("loaded string : " + dic["ver"]); Console.ReadKey(); } dic = new Dictionary <string, string>(); dic["ver"] = ver; using (StreamWriter sr = new System.IO.StreamWriter(filePath, false, Encoding.UTF8)) { sr.WriteLine( CustomEncode.ToBase64String( BinarySerialize.ObjectToBytes(dic))); } }
/// <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>仲介コードから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()); }
public static void FromBase64StringTest(string base64Str) { string base64Decoded; //convert to byte using components of Touryo byte[] data = CustomEncode.FromBase64String(base64Str); //convert to string unsing components of Touryo base64Decoded = CustomEncode.ToBase64String(data); //check whether the two strings are equal. Assert.AreEqual(base64Str, base64Decoded); }
public static void ToBase64StringTest(byte[] aryByt) { string base64Decoded; //convert to byte using components of Touryo base64Decoded = CustomEncode.ToBase64String(aryByt); //convert to string using components of Touryo byte[] data = CustomEncode.FromBase64String(base64Decoded); //check whether it is converted to original byte Assert.AreEqual(aryByt, data); }
/// <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); } }
static void Main(string[] args) { string iss = OAuth2AndOIDCParams.Isser; string aud = OAuth2AndOIDCParams.Audience; string scopes = "hoge1 hoge2 hoge3"; JObject jobj = null; JWS_RS256_XML jws_RS256 = new JWS_RS256_XML(); Console.WriteLine("PrivateKey:"); Console.WriteLine(CustomEncode.ToBase64String( CustomEncode.StringToByte(jws_RS256.XMLPrivateKey, CustomEncode.us_ascii))); Console.WriteLine(""); Console.WriteLine("PublicKey:"); Console.WriteLine(CustomEncode.ToBase64String( CustomEncode.StringToByte(jws_RS256.XMLPublicKey, CustomEncode.us_ascii))); Console.WriteLine(""); string jwtAssertion = JwtAssertion.CreateJwtBearerTokenFlowAssertion( OAuth2AndOIDCParams.Isser, OAuth2AndOIDCParams.Audience, new System.TimeSpan(0, 30, 0), scopes, jws_RS256.XMLPrivateKey); if (JwtAssertion.VerifyJwtBearerTokenFlowAssertion( jwtAssertion, out iss, out aud, out scopes, out jobj, jws_RS256.XMLPublicKey)) { if (iss == OAuth2AndOIDCParams.Isser && aud == OAuth2AndOIDCParams.Audience) { Console.WriteLine("JwtAssertion:"); Console.WriteLine(jwtAssertion); Console.WriteLine(""); Console.ReadLine(); return; } } Console.WriteLine("Error"); Console.ReadLine(); }
static void Main(string[] args) { string iss = GetConfigParameter.GetConfigValue("iss"); string aud = GetConfigParameter.GetConfigValue("aud"); string scopes = "hoge1 hoge2 hoge3"; JObject jobj = null; JWT_RS256_XML jwt_RS256 = new JWT_RS256_XML(); Console.WriteLine("PrivateKey:"); Console.WriteLine(CustomEncode.ToBase64String( CustomEncode.StringToByte(jwt_RS256.XMLPrivateKey, CustomEncode.us_ascii))); Console.WriteLine(""); Console.WriteLine("PublicKey:"); Console.WriteLine(CustomEncode.ToBase64String( CustomEncode.StringToByte(jwt_RS256.XMLPublicKey, CustomEncode.us_ascii))); Console.WriteLine(""); string jwtAssertion = JwtAssertion.CreateJwtBearerTokenFlowAssertion( GetConfigParameter.GetConfigValue("iss"), GetConfigParameter.GetConfigValue("aud"), new System.TimeSpan(0, 30, 0), scopes, jwt_RS256.XMLPrivateKey); if (JwtAssertion.VerifyJwtBearerTokenFlowAssertion( jwtAssertion, out iss, out aud, out scopes, out jobj, jwt_RS256.XMLPublicKey)) { if (iss == GetConfigParameter.GetConfigValue("iss") && aud == GetConfigParameter.GetConfigValue("aud")) { Console.WriteLine("JwtAssertion:"); Console.WriteLine(jwtAssertion); Console.WriteLine(""); Console.ReadLine(); return; } } Console.WriteLine("Error"); Console.ReadLine(); }
/// <summary>EncodeAndSignPost</summary> /// <param name="saml">string</param> /// <param name="referenceId">string</param> /// <param name="rsa">RSA</param> /// <returns>RedirectPost用SAML文字列</returns> public static string EncodeAndSignPost(string saml, string referenceId = "", RSA rsa = null) { //// エンコーディング オブジェクトの取得 //Encoding enc = XmlLib.GetEncodingFromXmlDeclaration(saml); if (rsa == null) { // 署名しない } else { // 署名する SignedXml2 signedXml2 = new SignedXml2(rsa); saml = signedXml2.Create(saml, referenceId).OuterXml; } // XML (→ XML宣言のエンコーディングではなく、asciiエンコーディングに変更) → Base64エンコード return(CustomEncode.ToBase64String(CustomEncode.StringToByte( saml, CustomEncode.us_ascii))); //enc.CodePage)); }
/// <summary>パスワードを比較して認証する。</summary> /// <param name="rawPassword">Password entered by the user.</param> /// <param name="saltedPassword">Salted and hashed password.</param> /// <param name="ekha">ハッシュ・アルゴリズム列挙型</param> /// <returns> /// true:パスワードは一致した。 /// false:パスワードは一致しない。 /// </returns> public static bool EqualSaltedPassword(string rawPassword, string saltedPassword, EnumKeyedHashAlgorithm ekha) { // ソルト部分を取得 string[] temp = saltedPassword.Split('.'); // key string key = CustomEncode.ByteToString(CustomEncode.FromBase64String(temp[0]), CustomEncode.UTF_8); // saltByte byte[] saltByte = CustomEncode.FromBase64String(temp[1]); // salt string salt = CustomEncode.ByteToString(saltByte, CustomEncode.UTF_8); // stretchCount int stretchCount = int.Parse(CustomEncode.ByteToString(CustomEncode.FromBase64String(temp[2]), CustomEncode.UTF_8)); // Salted and hashed password string hashedPassword = temp[3]; // KeyedHashのキーを生成する。 Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes(key, saltByte, stretchCount); // 引数のsaltedPasswordと、rawPasswordから自作したsaltedPasswordを比較 string compare = CustomEncode.ToBase64String( GetPasswordHashV2.GetKeyedHashBytes( CustomEncode.StringToByte(salt + rawPassword, CustomEncode.UTF_8), ekha, passwordKey.GetBytes(24))); if (hashedPassword == compare) { // 一致した。 return(true); } else { // 一致しなかった。 return(false); } }
/// <summary>Refresh Tokenを使用してAccess Tokenを更新する。</summary> /// <param name="tokenEndpointUri">tokenEndpointUri</param> /// <param name="client_id">client_id</param> /// <param name="client_secret">client_secret</param> /// <param name="refreshToken">refreshToken</param> /// <returns>結果のJSON文字列</returns> public async Task <string> UpdateAccessTokenByRefreshTokenAsync( Uri tokenEndpointUri, string client_id, string client_secret, string refreshToken) { // 6. アクセストークンの更新 // http://openid-foundation-japan.github.io/rfc6749.ja.html#token-refresh // 通信用の変数 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) httpRequestMessage.Content = new FormUrlEncodedContent( new Dictionary <string, string> { { "grant_type", ASPNETIdentityConst.RefreshTokenGrantType }, { "refresh_token", refreshToken }, }); // HttpResponseMessage httpResponseMessage = await _oAuthHttpClient.SendAsync(httpRequestMessage); return(await httpResponseMessage.Content.ReadAsStringAsync()); }
/// <summary>Base64Secretを生成</summary> /// <param name="byteSize">サイズ(バイト)</param> /// <returns>Base64Secret</returns> public static string Base64Secret(int byteSize) { return(CustomEncode.ToBase64String(GetPassword.RandomByte(byteSize))); }
public string GetAuthTicket(string encUid, string encPwd) { try { // ユーザIDの復号化 string uid = SymmetricCryptography.DecryptString( encUid, (string)Session["challenge"], EnumSymmetricAlgorithm.TripleDESCryptoServiceProvider); // パスワードの復号化 string pwd = SymmetricCryptography.DecryptString( encPwd, (string)Session["challenge"], EnumSymmetricAlgorithm.TripleDESCryptoServiceProvider); // 認証する。 bool isAuthenticated = false; #region 認証処理のUOC // ★★ コンテキストの情報を使用するなどして // 認証処理をUOCする(必要に応じて)。 //// B層・D層呼出し //// 認証チェックとタイムスタンプの更新 //MyUserInfo userInfo =new MyUserInfo( // "未認証:" + uid, HttpContext.Current.Request.UserHostAddress); //BaseReturnValue returnValue = (BaseReturnValue)Latebind.InvokeMethod( // "xxxx", "yyyy", // FxLiteral.TRANSMISSION_INPROCESS_METHOD_NAME, // new object[] { // new AuthParameterValue("-", "-", "zzzz", "",userInfo, pwd), // DbEnum.IsolationLevelEnum.User }); //// 認証されたか・されなかったか //isAuthenticated = !returnValue.ErrorFlag; isAuthenticated = true; #endregion if (isAuthenticated) { // 認証チケットを作成して暗号化する(DateTime.Nowにより可変に)。 string[] authTicket = { uid, pwd, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") }; return(SymmetricCryptography.EncryptString( CustomEncode.ToBase64String( BinarySerialize.ObjectToBytes(authTicket)), GetConfigParameter.GetConfigValue("private-key"), EnumSymmetricAlgorithm.TripleDESCryptoServiceProvider)); } else { // 認証失敗 return(string.Empty); } } catch { // 認証失敗 return(string.Empty); } finally { // セッションの解放 Session.Abandon(); } }