/// <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>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>ハッシュ化</summary> private void button11_Click(object sender, EventArgs e) { this.textBox12.Text = ""; this.textBox13.Text = ""; if (this.textBox11.Text == "") { return; } // ハッシュ(キー無し)サービスプロバイダ HashAlgorithm ha = this.CreateHashAlgorithmServiceProvider(); // 元文字列 string ss = this.textBox11.Text; //元文字列をbyte型配列に変換する(UTF-8 Enc) byte[] asb = Encoding.UTF8.GetBytes(ss); // ハッシュ値を計算する byte[] hb = ha.ComputeHash(asb); //結果を表示 // 生バイト this.textBox12.Text = CustomEncode.ToHexString(hb); // Base64 this.textBox13.Text = Convert.ToBase64String(hb); }
/// <summary>ChangeToIdTokenFromJwt</summary> /// <param name="access_token">Jwt (string)</param> /// <returns>IdToken (string)</returns> public static string ChangeToIdTokenFromJwt(string access_token) { if (access_token.Contains(".")) { string[] temp = access_token.Split('.'); string json = CustomEncode.ByteToString(CustomEncode.FromBase64UrlString(temp[1]), CustomEncode.UTF_8); Dictionary <string, object> authTokenClaimSet = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); // ・access_tokenがJWTで、payloadに"nonce" and "scope=openidクレームが存在する場合、 if (authTokenClaimSet.ContainsKey("nonce") && authTokenClaimSet.ContainsKey("scopes")) { JArray scopes = (JArray)authTokenClaimSet["scopes"]; // ・OpenID Connect : response_type=codeに対応する。 if (scopes.Any(x => x.ToString() == ASPNETIdentityConst.Scope_Openid)) { //・payloadからscopeを削除する。 authTokenClaimSet.Remove("scopes"); //・編集したpayloadを再度JWTとして署名する。 string newPayload = JsonConvert.SerializeObject(authTokenClaimSet); JWT_RS256 jwtRS256 = null; // 署名 jwtRS256 = new JWT_RS256(ASPNETIdentityConfig.OAuthJWT_pfx, ASPNETIdentityConfig.OAuthJWTPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); string id_token = jwtRS256.Create(newPayload); // 検証 jwtRS256 = new JWT_RS256(ASPNETIdentityConfig.OAuthJWT_cer, ASPNETIdentityConfig.OAuthJWTPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); if (jwtRS256.Verify(id_token)) { // 検証できた。 return(id_token); } else { // 検証できなかった。 } } else { // OIDCでない。 } } else { // OIDCでない。 } } else { // JWTでない。 } return(""); }
/// <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>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>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>Init</summary> /// <param name="jwkString">string</param> public void Init(string jwkString) { Dictionary <string, string> jwk = new Dictionary <string, string>(); jwk = JsonConvert.DeserializeObject <Dictionary <string, string> >(jwkString); if (jwk.ContainsKey(JwtConst.kty) && jwk.ContainsKey(JwtConst.use) && jwk.ContainsKey(JwtConst.alg) && jwk.ContainsKey(JwtConst.k)) { // 正しいキー if (jwk[JwtConst.kty].ToLower() == "oct" && jwk[JwtConst.use].ToLower() == "sig" && jwk[JwtConst.alg].ToUpper() == this.JwtConstHSnnn && !string.IsNullOrEmpty(jwk[JwtConst.k])) { // 正しい値 this.JWK = jwkString; this.Key = CustomEncode.FromBase64UrlString(jwk[JwtConst.k]); return; // 正常終了 } else { } } else { } // 異常終了 throw new ArgumentException( PublicExceptionMessage.ARGUMENT_INCORRECT, "The JWK of " + this.JwtConstHSnnn + " is incorrect."); }
/// <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>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>DecodeRedirect</summary> /// <param name="queryString">string</param> /// <returns>デコードされたsaml</returns> public static string DecodeRedirect(string queryString) { // EcodeRedirectの逆 // -------------------------------------------------- // Saml → URLデコード → Base64デコード // → DEFLATE解凍 → XML宣言のエンコーディング → XML // -------------------------------------------------- // Samlの抽出 string saml = ""; if (queryString.IndexOf("SAMLRequest") != -1) { saml = StringExtractor.GetParameterFromQueryString("SAMLRequest", queryString); } else if (queryString.IndexOf("SAMLResponse") != -1) { saml = StringExtractor.GetParameterFromQueryString("SAMLResponse", queryString); } else { return(""); } byte[] tempByte = DeflateCompression.Decompress( CustomEncode.FromBase64String(CustomEncode.UrlDecode(saml))); //// XML宣言部分を取得するために、us_asciiでデコード //string tempString = CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii); //// エンコーディング オブジェクトの取得 //Encoding enc = XmlLib.GetEncodingFromXmlDeclaration(tempString); return(CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii)); // enc.CodePage); }
/// <summary>JwkToParam</summary> /// <param name="jwkObject">JObject</param> /// <returns>RSAParameters(公開鍵)</returns> public RSAParameters JwkToParam(JObject jwkObject) { if (jwkObject[JwtConst.kty].ToString().ToUpper() == JwtConst.RSA) { // RSAParameters // FromBase64Stringだとエラーになる。 RSAParameters rsaParameters = new RSAParameters() { // Public Modulus = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.n]), Exponent = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.e]), // Private D = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.d]), P = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.p]), Q = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.q]), DP = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.dp]), DQ = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.dq]), InverseQ = CustomEncode.FromBase64UrlString((string)jwkObject[JwtConst.qi]) }; return(rsaParameters); } throw new ArgumentOutOfRangeException("jwkObject", jwkObject, "Invalid"); }
/// <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>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> /// 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>Constructor</summary> /// <param name="jwkString">string</param> public JWT_HS256(string jwkString) { Dictionary <string, string> jwk = new Dictionary <string, string>(); jwk = JsonConvert.DeserializeObject <Dictionary <string, string> >(jwkString); if (jwk.ContainsKey("kty") && jwk.ContainsKey("use") && jwk.ContainsKey("alg") && jwk.ContainsKey("k")) { // 正しいキー if (jwk["kty"] == "oct" && jwk["use"] == "sig" && jwk["alg"] == "HS256" && !string.IsNullOrEmpty(jwk["k"])) { // 正しい値 this.JWK = jwkString; this.Key = CustomEncode.FromBase64UrlString(jwk["k"]); return; // 正常終了 } else { } } else { } // 異常終了 throw new ArgumentException( PublicExceptionMessage.ARGUMENT_INCORRECT, "The JWK of HS256 is incorrect."); }
/// <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>GetBytesFromPemString</summary> /// <param name="pemString">string</param> /// <param name="label">string</param> /// <returns>Byte[]</returns> public static Byte[] GetBytesFromPemString(string pemString, string label) { string header = String.Format("-----BEGIN {0}-----", label); string footer = String.Format("-----END {0}-----", label); if (string.IsNullOrEmpty(header)) { return(null); } if (string.IsNullOrEmpty(footer)) { return(null); } int start = pemString.IndexOf(header, StringComparison.Ordinal); if (start < 0) { return(null); } start += header.Length; int end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start; if (end < 0) { return(null); } // X509Certificate2 return(CustomEncode.FromBase64String(pemString.Substring(start, end))); }
/// <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> /// <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>ハッシュ化</summary> private void button21_Click(object sender, EventArgs e) { this.textBox22.Text = ""; this.textBox23.Text = ""; if (this.textBox21a.Text == "" || this.textBox21b.Text == "") { return; } // ハッシュ(キー付き)サービスプロバイダ KeyedHashAlgorithm kha = this.CreateKeyedHashAlgorithmServiceProvider(); // 元文字列 string ss = this.textBox21a.Text; // 元文字列をbyte型配列に変換する(UTF-8 Enc) byte[] asb = Encoding.UTF8.GetBytes(ss); // キー文字列 string ks = this.textBox21b.Text; // キー文字列をbyte型配列に変換する(UTF-8 Enc) byte[] akb = Encoding.UTF8.GetBytes(ks); // ハッシュ値を計算する if (kha is HMACSHA1) { // どのサイズのキーでも受け入れる kha.Key = akb; } else if (kha is MACTripleDES) { // 長さが 16 または 24 バイトのキーを受け入れる if (akb.Length < 16) { MessageBox.Show("キーの長さが不足しています。"); return; } else if (akb.Length < 24) { kha.Key = PubCmnFunction.ShortenByteArray(akb, 16); } else { // 24バイトに切り詰め kha.Key = PubCmnFunction.ShortenByteArray(akb, 24); } } byte[] hb = kha.ComputeHash(asb); //結果を表示 // 生バイト this.textBox22.Text = CustomEncode.ToHexString(hb); // Base64 this.textBox23.Text = Convert.ToBase64String(hb); }
/// <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>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> /// <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> /// <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> 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>JwkToCng</summary> /// <param name="jwk">JObject</param> /// <returns>CngKey(公開鍵)</returns> public static CngKey JwkToCng(Dictionary <string, string> jwk) { // 楕円曲線 // 不要 // 公開鍵の部分 return(EccKey.New( CustomEncode.FromBase64UrlString((string)jwk[JwtConst.x]), CustomEncode.FromBase64UrlString((string)jwk[JwtConst.y]))); }
/// <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="privateKey">復号化に使用する秘密鍵</param> /// <returns>非対称アルゴリズムで復号化された文字列</returns> public static string DecryptString(string sourceString, string privateKey) { // 暗号化文字列をbyte型配列に変換する(Base64) byte[] source = CustomEncode.FromBase64String(sourceString); // 復号化(UTF-8 Enc) return(CustomEncode.ByteToString( ASymmetricCryptography.DecryptBytes(source, privateKey), CustomEncode.UTF_8)); }
/// <summary>暗号化された文字列を復号化する</summary> /// <param name="sourceString">暗号化された文字列</param> /// <param name="password">暗号化に使用したパスワード</param> /// <returns>復号化された文字列</returns> public string DecryptString( string sourceString, string password) { // 暗号化文字列をbyte型配列に変換する(Base64) byte[] source = CustomEncode.FromBase64String(sourceString); // 復号化(UTF-8 Enc) return(CustomEncode.ByteToString(this.DecryptBytes(source, password), CustomEncode.UTF_8)); }