Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
ddemland
Starting Member
4 Posts |
Posted - 2008-06-11 : 10:41:09
|
I am having a problem with some code I have in a DLL that is running in SQL Server 2005. I am trying to get some RSA encryption and decryption. The encrypt code runs in SAFE mode without a problem. The decrypt code gets and error:Msg 6522, Level 16, State 1, Line 1A .NET Framework error occurred during execution of user-defined routine or aggregate "March_CryptoDecrypt": System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.KeyContainerPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.System.Security.SecurityException: at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)at System.Security.CodeAccessPermission.Demand()at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters)at System.Security.Cryptography.RSA.FromXmlString(String xmlString)at Crypto.DoCrypto.Decrypt(String P_text, String P_privateKey)at SQLServerCrypto.Decrypt(SqlString P_text, SqlString P_privateKey)Here is the decrypt code: static public string Decrypt(string P_text, string P_privateKey) { string retStr; string encryptedBlock = ""; string localTextStr = P_text; int numberOfBlocks; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(); rsaProvider.FromXmlString(P_privateKey); Queue<string> encryptedBlocks = new Queue<string>(); while (localTextStr.Length != 0) { if (rsaProvider.KeySize == 1024) { encryptedBlock = localTextStr.Substring(0, localTextStr.IndexOf("=") + 1); encryptedBlocks.Enqueue(encryptedBlock); localTextStr = localTextStr.Remove(0, encryptedBlock.Length); } else { encryptedBlock = localTextStr.Substring(0, localTextStr.IndexOf("==") + 2); encryptedBlocks.Enqueue(encryptedBlock); localTextStr = localTextStr.Remove(0, encryptedBlock.Length); } } encryptedBlocks.TrimExcess(); numberOfBlocks = encryptedBlocks.Count; retStr = ""; for (int cnt = 1; cnt <= numberOfBlocks; cnt++) { encryptedBlock = encryptedBlocks.Dequeue(); retStr += ASCIIEncoding.ASCII.GetString(rsaProvider.Decrypt( Convert.FromBase64String(encryptedBlock), false)); } return (retStr); }Here is the encrypt code that works: static public string Encrypt(string P_text, string P_publicKey) { string retStr; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(); rsaProvider.FromXmlString(P_publicKey); int numberOfBlocks = (P_text.Length / 32) + 1; char[] charArray = P_text.ToCharArray(); byte[][] byteBlockArray = new byte[numberOfBlocks][]; int incrementer = 0; for (int cnt = 1; cnt <= numberOfBlocks; cnt++) { if (cnt == numberOfBlocks) { byteBlockArray[cnt - 1] = ASCIIEncoding.ASCII.GetBytes(charArray, incrementer, charArray.Length - incrementer); } else { byteBlockArray[cnt - 1] = ASCIIEncoding.ASCII.GetBytes(charArray, incrementer, 32); incrementer += 32; } } retStr = ""; for (int cnt = 0; cnt < byteBlockArray.Length; cnt++) { retStr += System.Convert.ToBase64String( rsaProvider.Encrypt(byteBlockArray[cnt], false)); } return (retStr); }I do not see why the encrypt can run is safe mode and the decrypt can not. Does anyone have any ideas?Thank You,David Demland |
|
AndrewMurphy
Master Smack Fu Yak Hacker
2916 Posts |
Posted - 2008-06-11 : 11:23:30
|
can you simplfy the decrypt code and put debug statements and see how far into the decrypt code you are getting...if at all?are they both in the same DLL? |
 |
|
ddemland
Starting Member
4 Posts |
Posted - 2008-06-11 : 11:57:50
|
quote: Originally posted by AndrewMurphy can you simplfy the decrypt code and put debug statements and see how far into the decrypt code you are getting...if at all?are they both in the same DLL?
Both methods are in the same DLL. The encrypt works fine, the decrypt throws the error. By the message in the error:at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters)at System.Security.Cryptography.RSA.FromXmlString(String xmlString)It is clear that the access problem is started with the call FromXmlString which takes the RSA key (in XML format) and coverts it to the internal parameters needed by the RSA object. My concern is that both methods have the line:rsaProvider.FromXmlString(P_privateKey);The decrypt method throws the error and the encrypt method does not throw the error. It should be noted that both these methods are wrapped to give an interface to SQL Server. The wrapping code looks like: [SqlFunction()] static public SqlString Encrypt(SqlString P_text, SqlString P_publicKey) { string text = P_text.ToString(); string pubKey = P_publicKey.ToString(); string dataStr = DoCrypto.Encrypt(text, pubKey); SqlString retVal = new SqlString(dataStr); return (retVal); } [SqlFunction()] static public SqlString Decrypt(SqlString P_text, SqlString P_privateKey) { string text = P_text.ToString(); string privKey = P_privateKey.ToString(); string dataStr = DoCrypto.Decrypt(text, privKey); SqlString retVal = new SqlString(dataStr); return (retVal); }Due to the way the encrypt code blocks out the encryption I am not sure these is a way to simplify the decrypt code and still have it work properly. |
 |
|
ddemland
Starting Member
4 Posts |
Posted - 2008-06-11 : 13:51:15
|
How do I put debug statements into the code? It seems Console output fails because of the SAFE setting. I am lost at how I would output where the code is executing if I can not use Console outputs. |
 |
|
AndrewMurphy
Master Smack Fu Yak Hacker
2916 Posts |
Posted - 2008-06-12 : 09:15:36
|
I'm not about the specific's....I was looking at you simplifyin the code or putting in "WritetoNotepad file" type statements, basiacally saying i'm at line 1,2,3,4,etc. If the log only say At Line1At Line2At Line3then you know it's statement 4 which is failing.Have you tried calling this stuff outside SQL Server? |
 |
|
ddemland
Starting Member
4 Posts |
Posted - 2008-06-12 : 10:27:22
|
Here is the NUnit testing code for these methods: [Test] public void RunCryptoTests() { string publicKey = "<RSAKeyValue><Modulus>0VvEL0WnEzHylxgFac8WMAL7c9on1Xc+mn8yT8//XocjTFrJXNy5kag9Xs43gP0FxBCCOBOw9vrJu3duCvUMNkeLgRyoEqKUnX3auHP7f/zUUU8yhMLEPxJAJJdVh3Lq60e6okSOR6YBdsAFEa+jc/Wr37uO666RO0hAzIQ2BGRkXNh7mEsBn0cIzwzEB8EqT0DzOqink5kcSKmZ4eXCcLPbfvd1PD6kLG+Jzd7fO8vsxP7svsWtxH7foOd3fJ7y5+iagJ7kB4/E+escIwVYGIIBT1atEdSfIMUQnTBsgafOk7q9xNLLGlEqG65vUMlzYrLHu6XGtOO4nO98TD/noQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"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yDPVFJC8/CwUXFtxiWjuWk=</DQ><InverseQ>1IU0xcV1nvTcwGQaXiyN4rSBYkIsht1kSaLsiE53IgSx/pDltVHed4M+8GdWoT5Po0DE2/TYdtrY9actxzsRTQImh0uRGhQq3sN52HhABapyVv505MCkL8tYpyZJDo1mphAy2AfWTzAsJVfu+GzgC+yGSXk974uwsPnm0aidb4U=</InverseQ><D>I3WDeO43Kg0fpW+wGwe0HlWi+TBN5t3XgJtijhoQipYg6GHIES5hT8ZK/q+2vuYb/+U76PuM0YgQeuvze2+drePYQPn1jZJz0Wjrjqo2Qqsz2sGrMMk8K+KPcqMfHV3dZBQ2DB3Ia2I2hUJomWJCMPW/Mpm1zz014/CM6RbLf1qi8hB2dvxlzcM5Sz/08qFGxAlLRKP78GSh+zWOKxJ8qojKfWQYnxIg5FzGk95y2FGIIyV5WkQ7F1PIRgMymSbSpsR7XiQJcXU9qWn4CGSuZlTfOkFkgBz3cwfEg6f721sgjZbb+68MS3J8xiNdeqcQKkaICt1T0PNtYvPlH5tlAQ==</D></RSAKeyValue>"; string encryptText, realText; encryptText = DoCrypto.Encrypt("This is a test", publicKey); realText = DoCrypto.Decrypt(encryptText, privateKey); }The public and private keys were generated using the following code: RSACryptoServiceProvider RSAProvider; RSAProvider = new RSACryptoServiceProvider(2048); string publicAndPrivateKeys = RSAProvider.ToXmlString(true); string justPublicKey = RSAProvider.ToXmlString(false); try { StreamWriter streamWriter = new StreamWriter(".\\Private.key", false ); streamWriter.Write(publicAndPrivateKeys); streamWriter.Close(); } catch (System.Exception P_ex) { System.Console.WriteLine(P_ex.Message); } try { StreamWriter streamWriter = new StreamWriter(".\\Public.key", false ); streamWriter.Write(justPublicKey); streamWriter.Close(); } catch (System.Exception P_ex) { System.Console.WriteLine(P_ex.Message); }All this code has been running is a DLL. All I need to do is wrap the DLL code into a SQL Server function. I still have no idea how in one case the FromXmlString works and in the other it does not. |
 |
|
willskeat
Starting Member
1 Post |
Posted - 2010-05-11 : 10:05:22
|
i have a salvation of generating privatekeys for decryption.firstly you must find and open the web security config file that it must belongs to your ASP.NET security level(e.g. web_mediumtrust.config) in "\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG" folder.and finally you must write "<SecurityClass Name="KeyContainerPermission" Description="System.Security.Permissions.KeyContainerPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>" between already existing <SecurityClasses></SecurityClasses> tags. then in the following tags you must find "<NamedPermissionSets></NamedPermissionSets>" tags and you must write "<IPermission class="KeyContainerPermission" version="1" Unrestricted="true"/>" between this tags. |
 |
|
AndrewMurphy
Master Smack Fu Yak Hacker
2916 Posts |
Posted - 2010-05-11 : 10:51:27
|
Admins? Is this advice encouraged/valid, especially on a 18 month old topic? |
 |
|
|
|
|
|
|