/
Class1.cs
338 lines (278 loc) · 12.8 KB
/
Class1.cs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using System.Text;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Agreement.Kdf;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Paddings;
using System.Linq;
using Org.BouncyCastle.Crypto.Modes;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
namespace cryptoSQL
{
static class BCFunctions
{
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static AsymmetricCipherKeyPair GenerateKeys(int keySize)
{
var gen = new ECKeyPairGenerator();
var secureRandom = new SecureRandom();
var keyGenParam = new KeyGenerationParameters(secureRandom, keySize);
gen.Init(keyGenParam);
var key = gen.GenerateKeyPair();
var d = BitConverter.ToString(((ECPrivateKeyParameters)key.Private).D.ToByteArray()).Replace("-", "");
var q = BitConverter.ToString(((ECPublicKeyParameters)key.Public).Q.GetEncoded()).Replace("-", "");
var r = "<sqroot><D>" + d + "</D><Q>" + q + "</Q></sqroot>";
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static string RetrievePublicKey(string keySize, BigInteger d)
{
X9ECParameters ecParams = NistNamedCurves.GetByName("P-" + keySize);
ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());
//public key
ECPoint q = domainParameters.G.Multiply(d);
ECPublicKeyParameters pubkeyParam = new ECPublicKeyParameters(q, domainParameters);
return Convert.ToBase64String(pubkeyParam.Q.GetEncoded());
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static SqlBoolean VerifySignature(AsymmetricCipherKeyPair key, SqlString plainText, SqlString signature)
{
byte[] signatureBytes = Encoding.ASCII.GetBytes(signature.ToString());
var inputData = Encoding.ASCII.GetBytes(plainText.ToString());
var signer = SignerUtilities.GetSigner("ECDSA");
signer.Init(false, key.Public);
signer.BlockUpdate(inputData, 0, inputData.Length);
return signer.VerifySignature(signatureBytes);
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static byte[] GetSignature(string plainText, ICipherParameters privateKey)
//private static byte[] GetSignature(string plainText, AsymmetricCipherKeyPair key)
{
/* Init alg */
var signer = SignerUtilities.GetSigner("ECDSA");
/* Populate key */
//signer.Init(true, key.Private);
signer.Init(true, privateKey);
/* Get the bytes to be signed from the string */
var bytes = Encoding.UTF8.GetBytes(plainText);
/* Calc the signature */
signer.BlockUpdate(bytes, 0, bytes.Length);
byte[] signature = signer.GenerateSignature();
/* Base 64 encode the sig so its 8-bit clean */
//var signedString = Convert.ToBase64String(signature);
//return signedString;
return signature;
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static byte[] Hash(SqlString text, SqlString key)
{
var hmac = new HMac(new Sha256Digest());
hmac.Init(new KeyParameter(Encoding.UTF8.GetBytes(key.ToString())));
byte[] result = new byte[hmac.GetMacSize()];
byte[] bytes = Encoding.UTF8.GetBytes(text.ToString());
hmac.BlockUpdate(bytes, 0, bytes.Length);
hmac.DoFinal(result, 0);
return result;
}
public static Byte[] getSharedSecret(Byte[] PrivateKeyIn, Byte[] PublicKeyIn)
{
ECDHCBasicAgreement agreement = new ECDHCBasicAgreement();
X9ECParameters curve = null;
ECDomainParameters ecParam = null;
ECPrivateKeyParameters privKey = null;
ECPublicKeyParameters pubKey = null;
ECPoint point = null;
curve = NistNamedCurves.GetByName("P-256");
ecParam = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
privKey = new ECPrivateKeyParameters(new BigInteger(PrivateKeyIn), ecParam);
point = ecParam.Curve.DecodePoint(PublicKeyIn);
pubKey = new ECPublicKeyParameters(point, ecParam);
agreement.Init(privKey);
BigInteger secret = agreement.CalculateAgreement(pubKey);
return secret.ToByteArrayUnsigned();
}
public static byte[] DeriveSymmetricKeyFromSharedSecret(byte[] sharedSecret)
{
ECDHKekGenerator egH = new ECDHKekGenerator(DigestUtilities.GetDigest("SHA256"));
egH.Init(new DHKdfParameters(NistObjectIdentifiers.Aes, sharedSecret.Length, sharedSecret));
byte[] symmetricKey = new byte[DigestUtilities.GetDigest("SHA256").GetDigestSize()];
egH.GenerateBytes(symmetricKey, 0, symmetricKey.Length);
return symmetricKey;
}
}
static class BCDES
{
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static byte[] EncryptDES(byte[] data, byte[] derivedKey)
{
byte[] output = null;
try
{
KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DES", derivedKey);
IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/ISO7816_4PADDING");
cipher.Init(true, keyparam);
try
{
output = cipher.DoFinal(data);
return output;
}
catch (System.Exception ex)
{
throw new CryptoException(ex.Message);
}
}
catch (Exception ex)
{
}
return output;
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static byte[] DecryptDES(byte[] cipherData, byte[] derivedKey)
{
byte[] output = null;
try
{
KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DES", derivedKey);
IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/ISO7816_4PADDING");
cipher.Init(false, keyparam);
try
{
output = cipher.DoFinal(cipherData);
}
catch (System.Exception ex)
{
throw new CryptoException(ex.Message);
}
}
catch (Exception ex)
{
}
return output;
}
}
static class BCAES
{
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static byte[] EncryptAES(byte[] inputBytes, byte[] key, byte[] iVector)
{
//Convert.FromBase64String(keyString);
//Set up
byte[] iv = new byte[16];
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
KeyParameter keyParam = new KeyParameter(key);
ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);
// Encrypt
cipher.Init(true, keyParamWithIV);
byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
cipher.DoFinal(outputBytes, length); //Do the final block
//string encryptedInput = Convert.ToBase64String(outputBytes);
cipher.Init(false, keyParamWithIV);
byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length); //Do the final block
return outputBytes;
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static byte[] DecryptAES(byte[] outputBytes, byte[] key, byte[] iVector)
{
byte[] iv = iVector; //new byte[16];
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
KeyParameter keyParam = new KeyParameter(key);
ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);
//Decrypt
cipher.Init(false, keyParamWithIV);
byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
int length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length); //Do the final block
return comparisonBytes;
}
}
public class BC2F
{
private readonly Encoding _encoding;
private readonly IBlockCipher _blockCipher;
private PaddedBufferedBlockCipher _cipher;
private IBlockCipherPadding _padding;
public BC2F()
{
}
BC2F(IBlockCipher blockCipher, Encoding encoding)
{
_blockCipher = blockCipher;
_encoding = encoding;
}
#region Public Methods
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static string Encrypt2F(string TextPlain, string Password, byte[] Salt)
{
Sha3Digest Sha3Digest = new Sha3Digest();
Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator(Sha3Digest);
gen.Init(Encoding.UTF8.GetBytes(Password), Salt, 1000);
KeyParameter param = (KeyParameter)gen.GenerateDerivedParameters(new TwofishEngine().AlgorithmName, 256);
BC2F bcEngine = new BC2F(new TwofishEngine(), Encoding.UTF8);
bcEngine.SetPadding(new Pkcs7Padding());
return bcEngine.Encrypt(TextPlain, param);
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static string Decrypt2F(string TextEncripted, string Password, byte[] Salt)
{
Sha3Digest Sha3Digest = new Sha3Digest();
Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator(Sha3Digest);
gen.Init(Encoding.UTF8.GetBytes(Password), Salt, 1000);
KeyParameter param = (KeyParameter)gen.GenerateDerivedParameters(new TwofishEngine().AlgorithmName, 256);
BC2F bcEngine = new BC2F(new TwofishEngine(), Encoding.UTF8);
bcEngine.SetPadding(new Pkcs7Padding());
return bcEngine.Decrypt(TextEncripted, param);
}
#endregion
#region Private Methods
void SetPadding(IBlockCipherPadding padding)
{
if (padding != null)
_padding = padding;
}
string Encrypt(string plain, ICipherParameters SetKeyParameter)
{
byte[] result = BouncyCastleCrypto(true, _encoding.GetBytes(plain), SetKeyParameter);
return Convert.ToBase64String(result);
}
string Decrypt(string cipher, ICipherParameters SetKeyParameter)
{
byte[] result = BouncyCastleCrypto(false, Convert.FromBase64String(cipher), SetKeyParameter);
return _encoding.GetString(result, 0, result.Length);
}
byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters SetKeyParameter)
{
try
{
_cipher = _padding == null ?
new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);
_cipher.Init(forEncrypt, SetKeyParameter);
byte[] ret = _cipher.DoFinal(input);
return ret;
}
catch (CryptoException ex)
{
Console.Write(ex.Message);
//MessageBox(ex.Message);
}
return null;
}
#endregion
}
}