summaryrefslogtreecommitdiffstats
path: root/samples/OAuth2ProtectedWebApi/Code/MemoryCryptoKeyStore.cs
blob: 2bed4fd2e5be3c39f62ac863e3e886edcf784de4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
namespace OAuth2ProtectedWebApi.Code {
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Web;

	using DotNetOpenAuth.Messaging.Bindings;

	internal class MemoryCryptoKeyStore : ICryptoKeyStore {
		private Dictionary<string, Dictionary<string, CryptoKey>> keys = new Dictionary<string, Dictionary<string, CryptoKey>>();

		private MemoryCryptoKeyStore() {
		}

		internal static ICryptoKeyStore Instance = new MemoryCryptoKeyStore();

		public CryptoKey GetKey(string bucket, string handle) {
			Dictionary<string, CryptoKey> keyBucket;
			if (this.keys.TryGetValue(bucket, out keyBucket)) {
				CryptoKey key;
				if (keyBucket.TryGetValue(handle, out key)) {
					return key;
				}
			}

			return null;
		}

		public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
			Dictionary<string, CryptoKey> keyBucket;
			if (this.keys.TryGetValue(bucket, out keyBucket)) {
				foreach (var cryptoKey in keyBucket) {
					yield return cryptoKey;
				}
			}
		}

		public void StoreKey(string bucket, string handle, CryptoKey key) {
			Dictionary<string, CryptoKey> keyBucket;
			if (!this.keys.TryGetValue(bucket, out keyBucket)) {
				keyBucket = this.keys[bucket] = new Dictionary<string, CryptoKey>();
			}

			keyBucket[handle] = key;
		}

		public void RemoveKey(string bucket, string handle) {
			Dictionary<string, CryptoKey> keyBucket;
			if (this.keys.TryGetValue(bucket, out keyBucket)) {
				keyBucket.Remove(handle);
			}
		}
	}
}