473,721 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

2.0 breaking change. Can't figure it out.

This code worked on fx 1.1 and now I get a "Keyset does not exist" error
when trying to SignData with RSA under FX2.0.
Smells like some security error, but can't debug it as I think error is
thrown in win32. If you create a new RSA, it works. But creating RSA from
an SNK does not work.

string privSnk = @"v:\wsesimplet cpdll\wsesimple tcpdll.snk"; // Use any snk
file.
System.Security .Cryptography.R SACryptoService Provider rsa =
SnkUtil.GetRSAF romSnkFile(priv Snk);
byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
byte[] sig = rsa.SignData(da ta, new SHA1CryptoServi ceProvider());

// Error on line 4 (i.e. rsa.SignData)
System.Security .Cryptography.C ryptographicExc eption was unhandled
Message="Keyset does not exist\r\n"
Source="mscorli b"
StackTrace:
at
System.Security .Cryptography.C ryptographicExc eption.ThrowCry ptogaphicExcept ion(Int32
hr)
....

// SnkUtil Class
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Reflecti on;
using System.Security .Cryptography;
using System.Collecti ons;

namespace WSESimpleTCPDLL
{
/// <summary>
/// One static method to get an RSACryptoServic eProvider from a *.snk file.
/// NOTE: These methods assume 1024 bit keys, the same as exported from
sn.exe.
/// </summary>
public sealed class SnkUtil
{
#region Fields
private const int magic_priv_idx = 0x08;
private const int magic_pub_idx = 0x14;
private const int magic_size = 4;
#endregion

#region Constructors
private SnkUtil()
{
}
#endregion

#region Public Methods
/// <summary>
/// Returns RSA object from *.snk key file.
/// </summary>
/// <param name="path">Pat h to snk file.</param>
/// <returns>RSACry ptoServiceProvi der</returns>
public static RSACryptoServic eProvider GetRSAFromSnkFi le(string path)
{
if ( path == null )
throw new ArgumentNullExc eption("path");

byte[] snkBytes = GetFileBytes(pa th);
if ( snkBytes == null )
throw new Exception("Inva lid SNK file.");

RSACryptoServic eProvider rsa = GetRSAFromSnkBy tes(snkBytes);
return rsa;
}

public static RSACryptoServic eProvider GetPublicKeyFro mAssembly(Assem bly
assembly)
{
if ( assembly == null )
throw new ArgumentNullExc eption("assembl y");

byte[] pubkey = assembly.GetNam e().GetPublicKe y();
if ( pubkey.Length == 0 )
throw new Exception("No public key in assembly.");

RSAParameters p = SnkUtil.GetRSAP arameters(pubke y);
RSACryptoServic eProvider rsa = new RSACryptoServic eProvider();
rsa.ImportParam eters(p);
return rsa;
}

/// <summary>
/// Returns RSAParameters from byte[].
/// Example to get rsa public key from assembly:
/// byte[] pubkey =
System.Reflecti on.Assembly.Get ExecutingAssemb ly().GetName(). GetPublicKey();
/// RSAParameters p = SnkUtil.GetRSAP arameters(pubke y);
/// </summary>
/// <param name="keypair"> </param>
/// <returns></returns>
public static RSAParameters GetRSAParameter s(byte[] keyBytes)
{
RSAParameters ret = new RSAParameters() ;

if ((keyBytes == null) || (keyBytes.Lengt h < 1))
throw new ArgumentNullExc eption("keyByte s");

bool pubonly = SnkBufIsPubLeng th(keyBytes);

if ((pubonly) && (!CheckRSA1(key Bytes)))
return ret;

if ((!pubonly) && (!CheckRSA2(key Bytes)))
return ret;

int magic_idx = pubonly ? magic_pub_idx : magic_priv_idx;

// Bitlen is stored here, but note this
// class is only set up for 1024 bit length keys
int bitlen_idx = magic_idx + magic_size;
int bitlen_size = 4; // DWORD

// Exponent
// In read file, will usually be { 1, 0, 1, 0 } or 65537
int exp_idx = bitlen_idx + bitlen_size;
int exp_size = 4;
//BYTE modulus[rsapubkey.bitle n/8]; == MOD; Size 128
int mod_idx = exp_idx + exp_size;
int mod_size = 128;

//BYTE prime1[rsapubkey.bitle n/16]; == P; Size 64
int p_idx = mod_idx + mod_size;
int p_size = 64;

//BYTE prime2[rsapubkey.bitle n/16]; == Q; Size 64
int q_idx = p_idx + p_size;
int q_size = 64;

//BYTE exponent1[rsapubkey.bitle n/16]; == DP; Size 64
int dp_idx = q_idx + q_size;
int dp_size = 64;

//BYTE exponent2[rsapubkey.bitle n/16]; == DQ; Size 64
int dq_idx = dp_idx + dp_size;
int dq_size = 64;

//BYTE coefficient[rsapubkey.bitle n/16]; == InverseQ; Size 64
int invq_idx = dq_idx + dq_size;
int invq_size = 64;

//BYTE privateExponent[rsapubkey.bitle n/8]; == D; Size 128
int d_idx = invq_idx + invq_size;
int d_size = 128;
// Figure public params
// Must reverse order (little vs. big endian issue)
ret.Exponent = BlockCopy(keyBy tes, exp_idx, exp_size);
Array.Reverse(r et.Exponent);
ret.Modulus = BlockCopy(keyBy tes, mod_idx, mod_size);
Array.Reverse(r et.Modulus);

if (pubonly) return ret;

// Figure private params
// Must reverse order (little vs. big endian issue)
ret.P = BlockCopy(keyBy tes, p_idx, p_size);
Array.Reverse(r et.P);

ret.Q = BlockCopy(keyBy tes, q_idx, q_size);
Array.Reverse(r et.Q);

ret.DP = BlockCopy(keyBy tes, dp_idx, dp_size);
Array.Reverse(r et.DP);

ret.DQ = BlockCopy(keyBy tes, dq_idx, dq_size);
Array.Reverse(r et.DQ);

ret.InverseQ = BlockCopy(keyBy tes, invq_idx, invq_size);
Array.Reverse(r et.InverseQ);

ret.D = BlockCopy(keyBy tes, d_idx, d_size);
Array.Reverse(r et.D);

return ret;
}
#endregion

#region Private Methods
private static byte[] GetFileBytes(st ring path)
{
using ( FileStream fs = new FileStream(path , FileMode.Open,
FileAccess.Read ) )
using ( BinaryReader br = new BinaryReader(fs ) )
{
byte[] bytes = br.ReadBytes((i nt)fs.Length);
return bytes;
}
}

private static RSACryptoServic eProvider GetRSAFromSnkBy tes(byte[]
snkBytes)
{
if ( snkBytes == null )
throw new ArgumentNullExc eption("snkByte s");
RSAParameters param = GetRSAParameter s(snkBytes);

// Must set KeyNumber to AT_SIGNATURE for strong
// name keypair to be correctly imported.
CspParameters cp = new CspParameters() ;
cp.KeyNumber = 2; // AT_SIGNATURE

RSACryptoServic eProvider rsa = new RSACryptoServic eProvider(1024, cp);
rsa.ImportParam eters(param);
return rsa;
}

private static byte[] BlockCopy(byte[] source, int idx, int size)
{
if ( (source == null) || (source.Length < (idx + size)) )
return null;

byte[] ret = new byte[size];
Buffer.BlockCop y(source, idx, ret, 0, size);
return ret;
}

/// <summary>
/// Returns true if buffer length is public key size.
/// </summary>
/// <param name="keypair"> </param>
/// <returns></returns>
private static bool SnkBufIsPubLeng th(byte[] keypair)
{
if ( keypair == null )
return false;
return (keypair.Length == 160);
}

/// <summary>
/// Check that RSA1 is in header (public key only).
/// </summary>
/// <param name="keypair"> </param>
/// <returns></returns>
private static bool CheckRSA1(byte[] pubkey)
{
// Check that RSA1 is in header.
// R S A 1
byte[] check = new byte[] { 0x52, 0x53, 0x41, 0x31 };
return CheckMagic(pubk ey, check, magic_pub_idx);
}

/// <summary>
/// Check that RSA2 is in header (public and private key).
/// </summary>
/// <param name="keypair"> </param>
/// <returns></returns>
private static bool CheckRSA2(byte[] pubkey)
{
// Check that RSA2 is in header.
// R S A 2
byte[] check = new byte[] { 0x52, 0x53, 0x41, 0x32 };
return CheckMagic(pubk ey, check, magic_priv_idx) ;
}

private static bool CheckMagic(byte[] keypair, byte[] check, int idx)
{
byte[] magic = BlockCopy(keypa ir, idx, magic_size);
if ( magic == null )
return false;

for (int i = 0; i < magic_size; i++)
{
if ( check[i] != magic[i] )
return false;
}

return true;
}
#endregion
}
}

--
William Stacey [MVP]

Nov 17 '05 #1
0 1625

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
31415
by: The Bicycling Guitarist | last post by:
Hi. I found the following when trying to learn if there is such a thing as a non-breaking hyphen. Apparently Unicode has a ‑ but that is not well-supported, especially in older browsers. Somebody somewhere said: Alternately, you can use CSS to declare a class having: ..nowrap { white-space:nowrap } .... and then wrap the compound word in a <span class=nowrap></span> tag (or any other suitable inline tag). You can also try {...
22
8005
by: stevenkobes | last post by:
If a word has a hyphen in it, IE will permit a line break at the hyphen, but Firefox/Mozilla won't. Apparently the Firefox behavior is standards-compliant, but it is not what I want. Is there a way to denote a hyphen in HTML, that the line can be broken after? I've read some stuff about soft hyphens and non-breaking hyphens, but those seem like the opposite of what I'm looking for. I want a normal hyphen, that always appears, and I...
3
6411
by: frasmus44 | last post by:
I have searched this group for ways to create jumbo fonts in my Access forms and reports. Unlike MS Word and MS Excel, Access has a 127 point font limit. (About 1.75" tall) I'm referring to bound controls here, so pasting a bitmap into the form is not a solution. I am using Access 2000 (9.0.4402 SR-1). After playing with some ActiveX controls, I found the Microsoft Forms 2.0 textbox looked promising. I placed the control in a form and...
4
1348
by: John Wood | last post by:
I saw that Microsoft have released a list of breaking changes in .Net here: http://msdn.microsoft.com/netframework/programming/breakingchanges/runtime/default.aspx While this is useful, it seems to be missing a change that has broken a lot of my applications, relating to the order in which members are returned by reflection. At least I can't find it. I reported the bug on ladybug:...
150
6536
by: tony | last post by:
If you have any PHP scripts which will not work in the current releases due to breaks in backwards compatibility then take a look at http://www.tonymarston.net/php-mysql/bc-is-everything.html and see if you agree with my opinion or not. Tony Marston http://www.tonymarston.net
4
1755
by: m.shidoshi | last post by:
I was recently put in charge of heading up my company's website, and while I have a lot of experience on the design side of things, I'm still very new to the programming side. When I started, the website had just gotten a revision, but the site was an utter mess, so I've been trying to fix it up. As I've gone along, I've learned some aspects of PHP, but my knowledge is still very limited. Here is the problem I'm trying to fix. A backend...
49
2789
by: elmar | last post by:
Hi Clers, If I look at my ~200000 lines of C code programmed over the past 15 years, there is one annoying thing in this smart language, which somehow reduces the 'beauty' of the source code ;-): char *cp; void *vp; void **vpp;
4
4554
by: Rubin | last post by:
1) I want to show a breaking hyphen in Mozilla 1.5.0.4 How do I do that? "Unicode standard annex #14", <http://www.unicode.org/reports/tr14/>, defines 4 breaking hyphens. <quote> Breaking hyphens establish explicit break opportunities immediately after each occurrence.
20
6924
by: hippomedon | last post by:
Hello everyone, I'm looking for some advice on whether I should break the normalization rule. Normally, I would not consider it, but this seems to be a special case. I have created an "Outcomes Database" used to store response data from measures/ questionnaires for a longitudinal health study. It is essentially derived from Duane Hookom's Survey Database (thanks Duane!!!), with many modifications added to fit the needs of my lab.
0
9367
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9131
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8007
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6669
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5981
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4484
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.