コード例 #1
0
        public static string rsa_pubkey_encrypt(string pub_key, string data, KeyFormat format, int key_len = 1024)
        {
            var rsa_work = new KeyWorker(pub_key, false, format, key_len);
            var en_data  = rsa_work.Encrypt(data);

            return(en_data);
        }
コード例 #2
0
 public KeyWorker(string key, bool isPrivate, KeyFormat format = KeyFormat.XML, int key_len = 1024)
 {
     this._key       = key;
     this._format    = format;
     this._key_len   = key_len;
     this._isPrivate = isPrivate;
 }
コード例 #3
0
        public SecureString RetrievePrivateKey(SecureString apiKey, KeyFormat keyFormat = KeyFormat.OpenSsh)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("SafeguardA2AContext");
            }
            if (apiKey == null)
            {
                throw new ArgumentException("Parameter may not be null", nameof(apiKey));
            }

            var request = new RestRequest("Credentials", RestSharp.Method.GET)
                          .AddParameter("type", "PrivateKey", ParameterType.QueryString)
                          .AddParameter("keyFormat", keyFormat.ToString(), ParameterType.QueryString)
                          .AddHeader("Accept", "application/json")
                          .AddHeader("Authorization", $"A2A {apiKey.ToInsecureString()}");
            var response = _a2AClient.Execute(request);

            if (response.ResponseStatus != ResponseStatus.Completed)
            {
                throw new SafeguardDotNetException($"Unable to connect to web service {_a2AClient.BaseUrl}, Error: " +
                                                   response.ErrorMessage);
            }
            if (!response.IsSuccessful)
            {
                throw new SafeguardDotNetException(
                          "Error returned from Safeguard API, Error: " + $"{response.StatusCode} {response.Content}",
                          response.StatusCode, response.Content);
            }
            var json = JToken.Parse(response.Content);

            Log.Information("Successfully retrieved A2A private key.");
            return(json.Root.ToString().ToSecureString());
        }
コード例 #4
0
        public static string rsa_prikey_decrypt(string pri_key, string data, KeyFormat format, int key_len = 1024)
        {
            var rsa_work = new KeyWorker(pri_key, true, format, key_len);
            var de_data  = rsa_work.Decrypt(data);

            return(de_data);
        }
コード例 #5
0
ファイル: KeyFormatTests.cs プロジェクト: tthtun/Cirqus
        public void CanGetTypeById()
        {
            KeyFormat.For <int>("i-{Username}");
            KeyFormat.For <double>("d-guid");

            KeyFormat.GetTypeById("d-9EA4FEC2-AA9F-460A-A2B7-60903218149D").ShouldBe(typeof(double));
        }
コード例 #6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setUp() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SetUp()
        {
            KeyFormat keyFormat = mock(typeof(KeyFormat));

            when(keyFormat.valueSize()).thenReturn(Long.BYTES);
            when(_store.keyFormat()).thenReturn(keyFormat);
        }
コード例 #7
0
ファイル: RSAPrivateKey.cs プロジェクト: 19317362/acme.net
        public void WriteTo(Stream stream, KeyFormat format)
        {
            byte[] keyBytes;

            switch (format)
            {
            case KeyFormat.DER:
                keyBytes = ToDerBytes();
                break;

            case KeyFormat.PEM:
                keyBytes = Encoding.ASCII.GetBytes(ToPemString());
                break;

            case KeyFormat.DotNetXml:
                var rsa = RSA.Create();

                rsa.ImportParameters(Key);

                var xml = rsa.ToXmlString(true);

                keyBytes = Encoding.ASCII.GetBytes(xml);

                break;

            default:
                throw new Exception("Unsupported key format:" + format);
            }

            stream.Write(keyBytes, 0, keyBytes.Length);
        }
コード例 #8
0
ファイル: IdTests.cs プロジェクト: tthtun/Cirqus
 public void FailsWhenRegisteringTypesWithNoLiteralIdentifier()
 {
     Should.Throw <ParseException>(() =>
     {
         KeyFormat.For <object>("guid-sguid-{placeholder}-*");
     });
 }
コード例 #9
0
 protected RsaPrivateKey(string key, KeyFormat format)
     : base(key, format)
 {
     if (!mHasPrivateParameters)
     {
         throw new GoodIdException("This is not a private key.");
     }
 }
コード例 #10
0
ファイル: IdTests.cs プロジェクト: tthtun/Cirqus
        public void ParsingSGuidToSGuid()
        {
            var sguid = KeyFormat.ToSGuid(Guid.Parse("21952ee6-d028-433f-8634-94d6473275f0"));

            var id = new Id <object>(KeyFormat.FromString("prefix-sguid"), "prefix-" + sguid);

            id.ToString().ShouldBe("prefix-" + sguid);
        }
コード例 #11
0
        public static string rsa_prikey_sign(string pri_key, string en_data, KeyFormat format, int key_len = 1024)
        {
            var sign_block = deal_string.sha256(en_data).ToUpper();
            var rsa_work   = new KeyWorker(pri_key, true, format, key_len);
            var sign       = rsa_work.Encrypt(sign_block);

            return(sign);
        }
コード例 #12
0
        /// <summary>
        /// Default constructor
        /// </summary>
        public HmacDesignModel()
        {
            HmacChecked = true;
            Key         = "some kind of hash key";

            KeyFormat.Add(Format.Text.ToString());
            KeyFormat.Add(Format.Hex.ToString());
            KeyFormatSelected = Format.Text;
        }
コード例 #13
0
 public ControlSymmetricKey(string symmetricKey, KeyFormat keyform)
 {
     InitializeComponent();
     txtSecretKey.Text = symmetricKey;
     cbKeyForm.Items.Add(KeyFormat.Hexadecimal);
     cbKeyForm.Items.Add(KeyFormat.Base64Encoded);
     cbKeyForm.Items.Add(KeyFormat.Base64UrlEncoded);
     cbKeyForm.Items.Add(KeyFormat.OrdinaryString);
     cbKeyForm.SelectedItem = keyform;
 }
コード例 #14
0
ファイル: KeyExport.cs プロジェクト: 19317362/acme.net
        public void Save(RSAParameters key, string keyName, KeyFormat format)
        {
            var keyFileName = Path.Combine(basePath, $"{keyName}." + GetExtension(format));

            var privateKey = new RSAPrivateKey(key);

            using (var stream = File.OpenWrite(keyFileName))
            {
                privateKey.WriteTo(stream, format);
            }
        }
コード例 #15
0
        public void gen_rsa_key(int key_len, KeyFormat format)
        {
            if (key_len != 1024 && key_len != 2048)
            {
                return;
            }
            KeyPair keyPair = new KeyPair(key_len, format);

            this._pub_key = keyPair.PublicKey;
            this._pri_key = keyPair.PrivateKey;
        }
コード例 #16
0
ファイル: KeyExporter.cs プロジェクト: vincent-deng/acme.net
        private static string GetExtension(KeyFormat format)
        {
            switch (format)
            {
            case KeyFormat.Der: return("der");

            case KeyFormat.Pem: return("pem");

            default: throw new Exception("Unsupported key format:" + format);
            }
        }
コード例 #17
0
ファイル: TestCirqusTests.cs プロジェクト: tthtun/Cirqus
        public void EmitToAnyStream()
        {
            KeyFormat.For <object>("stream-*");

            Emit <object>("stream-id", new EventWithNoRoot());

            var @event = Context.History.Single();

            @event.ShouldBeOfType <EventWithNoRoot>();
            @event.Meta[DomainEvent.MetadataKeys.AggregateRootId].ShouldBe("stream-id");
            @event.Meta[DomainEvent.MetadataKeys.Owner].ShouldBe("System.Object, mscorlib");
        }
コード例 #18
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static <Key> DataProvider dataProvider(ReadableState<Key> store, java.util.concurrent.ConcurrentMap<Key, ChangeEntry> changes) throws java.io.IOException
        private static DataProvider DataProvider <Key>(ReadableState <Key> store, ConcurrentMap <Key, ChangeEntry> changes)
        {
            if (changes.Empty)
            {
                return(store.DataProvider());
            }
            else
            {
                KeyFormat <Key> keys = store.KeyFormat();
                return(new KeyValueMerger(store.DataProvider(), new UpdateProvider(SortedUpdates(keys, changes)), keys.KeySize(), keys.ValueSize()));
            }
        }
コード例 #19
0
        static byte[] ParseKey(string key, KeyFormat keyFormat)
        {
            switch (keyFormat)
            {
            case KeyFormat.Ascii:
                return(Encoding.ASCII.GetBytes(key));

            case KeyFormat.Base64:
                return(Convert.FromBase64String(key));
            }
            throw new NotSupportedException("Unsupported KeyFormat. Supported formats are: ASCII and Base64.");
        }
コード例 #20
0
 private void UpdateKeyParameter()
 {
     if (keyParameterControl is ControlSymmetricKey csk)
     {
         symmetricKey = csk.GetKey();
         keyform      = csk.GetKeyForm();
     }
     else if (keyParameterControl is ControlCertificate cc)
     {
         certificatePath     = cc.GetCertificatePath();
         certificatePassword = cc.GetCertificatePassword();
     }
 }
コード例 #21
0
ファイル: KeyExport.cs プロジェクト: 19317362/acme.net
        private static string GetExtension(KeyFormat format)
        {
            switch (format)
            {
            case KeyFormat.DER: return("der");

            case KeyFormat.DotNetXml: return("xml");

            case KeyFormat.PEM: return("pem");

            default: throw new Exception("Unsupported format:" + format);
            }
        }
コード例 #22
0
        public static List <string> CreateKeys(int keySize, KeyFormat keyFormat)
        {
            List <string> keys = new List <string>();

            switch (keyFormat)
            {
            case KeyFormat.XML: keys = XC.RSAUtil.RsaKeyGenerator.XmlKey(keySize); break;

            case KeyFormat.Pkcs1: keys = XC.RSAUtil.RsaKeyGenerator.Pkcs1Key(keySize, false); break;

            case KeyFormat.Pkcs8: keys = XC.RSAUtil.RsaKeyGenerator.Pkcs8Key(keySize, false); break;
            }

            return(keys);
        }
コード例 #23
0
        protected RsaPublicKey(string key, KeyFormat format)
        {
            switch (format)
            {
            case KeyFormat.PEM:
                var RSAParameters = Converters.PemToRsaParameters(key, out mHasPrivateParameters);
                mKey = RSA.Create();
                mKey.ImportParameters(RSAParameters);

                break;

            default:
                throw new GoodIdException("Unsupported key format");
            }
        }
コード例 #24
0
        private void BtnValidate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                SecurityKey             key     = null;

                var    jwtToken  = handler.ReadJwtToken(txtToken.Text);
                string algorithm = jwtToken.SignatureAlgorithm;
                if (algorithm.StartsWith("HS"))
                {
                    KeyFormat keyFormat = (KeyFormat)cbKeyFormat.SelectedItem;
                    string    base64key = ViewJwtGenerator.GetBase64Key(txtSecret.Text, keyFormat);
                    key = new SymmetricSecurityKey(Base64UrlEncoder.DecodeBytes(base64key));
                }
                else if (algorithm.StartsWith("RS"))
                {
                    key = new RsaSecurityKey(certificate.GetRSAPrivateKey());
                }
                else if (algorithm.StartsWith("ES"))
                {
                    key = new ECDsaSecurityKey(certificate.GetECDsaPrivateKey());
                }
                else
                {
                    throw new NotSupportedException($"The given algorithm {algorithm} is not yet supported for signature validation");
                }

                handler.ValidateToken(txtToken.Text, new TokenValidationParameters()
                {
                    IssuerSigningKey = key,
                    ValidateActor    = false,
                    ValidateIssuer   = false,
                    ValidateAudience = false,
                }, out SecurityToken token);
            }
            catch (Exception ex)
            {
                this.ShowInformation("Validation error", "There is an error when validating the signature.\n" + ex.Message);
                return;
            }
            this.ShowInformation("Validation OK", "This Json Web Token is validated.");
        }
コード例 #25
0
        internal static string GetBase64Key(string symmetricKey, KeyFormat keyform)
        {
            switch (keyform)
            {
            case KeyFormat.Base64Encoded:
                byte[] data = Convert.FromBase64String(symmetricKey);
                return(Base64UrlEncoder.Encode(data));

            case KeyFormat.Base64UrlEncoded:
                return(symmetricKey);

            case KeyFormat.Hexadecimal:
                data = GetStringFromHex(symmetricKey);
                return(Base64UrlEncoder.Encode(data));

            default:
                return(Base64UrlEncoder.Encode(symmetricKey));
            }
        }
コード例 #26
0
        public void WriteTo(Stream stream, KeyFormat format)
        {
            byte[] keyBytes;

            switch (format)
            {
            case KeyFormat.Der:
                keyBytes = ToDerBytes();
                break;

            case KeyFormat.Pem:
                keyBytes = Encoding.ASCII.GetBytes(ToPemString());
                break;

            default:
                throw new Exception("Unexpected key format:" + format);
            }

            stream.Write(keyBytes, 0, keyBytes.Length);
        }
コード例 #27
0
        /// <summary>
        /// 格式化私钥
        /// </summary>
        /// <param name="key"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string FormatPrivateKey(string key, KeyFormat format)
        {
            string flag = format == KeyFormat.pkcs1 ? "-----{0} RSA PRIVATE KEY-----" : "-----{0} PRIVATE KEY-----";

            if (key.StartsWith(string.Format(flag, "BEGIN")))
            {
                return(key);
            }
            int           pos   = 0;
            List <string> lines = new List <string>();

            lines.Add(string.Format(flag, "BEGIN"));
            key = key.Replace("\r", "").Replace("\n", "");
            while (pos < key.Length)
            {
                var count = key.Length - pos < 64 ? key.Length - pos : 64;
                lines.Add(key.Substring(pos, count));
                pos += count;
            }
            lines.Add(string.Format(flag, "END"));
            return(string.Join("\r\n", lines));
        }
コード例 #28
0
        public static string Create(string key, KeyFormat formater = KeyFormat.ToUpper)
        {
            string result;

            switch (formater)
            {
            case KeyFormat.None:
                result = FormsAuthentication.HashPasswordForStoringInConfigFile(key, "MD5");
                break;

            case KeyFormat.ToUpper:
                result = FormsAuthentication.HashPasswordForStoringInConfigFile(key.ToUpper(), "MD5");
                break;

            case KeyFormat.ToLower:
                result = FormsAuthentication.HashPasswordForStoringInConfigFile(key.ToLower(), "MD5");
                break;

            default:
                result = null;
                break;
            }
            return(result);
        }
コード例 #29
0
        private static sbyte[][] SortedUpdates <Key>(KeyFormat <Key> keys, ConcurrentMap <Key, ChangeEntry> changes)
        {
            Entry[] buffer = new Entry[changes.size()];
            IEnumerator <KeyValuePair <Key, ChangeEntry> > entries = changes.entrySet().GetEnumerator();

            for (int i = 0; i < buffer.Length; i++)
            {
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                KeyValuePair <Key, ChangeEntry> next = entries.next();                        // we hold the lock, so this should succeed
                sbyte[] key = new sbyte[keys.KeySize()];
                keys.WriteKey(next.Key, new BigEndianByteArrayBuffer(key));
                buffer[i] = new Entry(key, next.Value.data);
            }
            Arrays.sort(buffer);
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            Debug.Assert(!entries.hasNext(), "We hold the lock, so we should see 'size' entries.");
            sbyte[][] result = new sbyte[buffer.Length * 2][];
            for (int i = 0; i < buffer.Length; i++)
            {
                result[i * 2]     = buffer[i].Key;
                result[i * 2 + 1] = buffer[i].Value;
            }
            return(result);
        }
コード例 #30
0
 internal KeyPair(RSACryptoServiceProvider rsa, KeyFormat format)
 {
     this._rsa = rsa;
     this._format = format;
 }
コード例 #31
0
 protected EncryptionKey(KeyFormat format)
 {
     Format = format;
 }
コード例 #32
0
        /// <summary>
        /// for java
        /// </summary>
        /// <returns></returns>
        static public KeyPair GenerateKeyPair(KeyFormat format = KeyFormat.XML, int keySize = 1024)
        {
            KeyPair keyPair = new KeyPair(new RSACryptoServiceProvider(keySize), format);

            return keyPair;
        }
コード例 #33
0
 static byte[] ParseKey(string key, KeyFormat keyFormat)
 {
     switch (keyFormat)
     {
         case KeyFormat.Ascii:
             return Encoding.ASCII.GetBytes(key);
         case KeyFormat.Base64:
             return Convert.FromBase64String(key);
     }
     throw new NotSupportedException("Unsupported KeyFormat");
 }
コード例 #34
0
 public KeyWorker(string key, KeyFormat format)
 {
     this._key = key;
     this._format = format;
 }