ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us    

Facebook   


MAIN MENU
News
Php Tips
Android Programming
Design Pattern By PHP
C# using Linq น่าใช้จริงๆ
C# Tips & Technique
C# Design Pattern
Linux Quick Tips
Java & JavaScript Tips
Database & SQL
ZengCode Framework Guide
Zeng Code Code
Programming
IPhone (Tips and Trick)

Download เอกสารที่น่าสนใจ

     Symmetric Encryption: .NET, CryptoAPI and Java 2  (2009-10-27)

This article discusses compatibility of symmetric key encryption using .NET 1.1, CryptoAPI and Java 2. A specific example using Triple DES encryption is used to demonstrate generating the identical ciphertext using CryptoAPI, .NET and Java 2.

(1) CryptoAPI Symmetric Encryption:

We start by generating a RSA "ExponentOfOne" keypair using the procedure and sample code provided at: HOWTO: Export/Import PlainText Session Key Using CryptoAPI. This will allow us to access the key material of a randomly generated symmetric key on any Windows platform, using CryptExportKey() with SIMPLEBLOB. (Exporting session keys as PLAINTEXTKEYBLOB is only supported on WinXP+). Using an ExponentOfOne RSA asymmetric key means that the encryption block of the exported SIMPLEBLOB is not actually encrypted at all, so we can easily extract the symmetric key bytes for use and comparison with encryption in .NET and Java 2.

Using the symmetric encryption C sample code from: Example C Program: Encrypting a File and changing the algorithm to CALG_3DES and specifying an Initialization Vector, the basic changes are:

  #define ENCRYPT_ALGORITHM  CALG_3DES 
  LPCSTR KeyContainer = "myExponentOfOneContainer"; 
  BYTE  pIV[] = {50,51,52,53,54,55,56,57} ;  //simple test IV for 3DES

  CryptAcquireContext(&hCryptProv, KeyContainer, MS_ENHANCED_PROV, PROV_RSA_FULL, 0);
  ....
  CryptGenKey(hCryptProv, ENCRYPT_ALGORITHM, CRYPT_EXPORTABLE, &hKey) ;
  ...
  CryptSetKeyParam(hKey, KP_IV, pIV, 0) ; 
  ...
  CryptGetUserKey(hCryptProv, AT_KEYEXCHANGE, &hXchgExpOneKey) ;
  ...
     
  CryptExportKey(hKey, hXchgExpOneKey, SIMPLEBLOB, 0, pbKeyBlob, &dwKeyBlobLen) ;
  //write SIMPLEBLOB key to file ...
  //encrypt the data with random-generated symmetric key and specified IV
  CryptEncrypt(hKey, .... 
  

For a randomly generated symmetric key, the referenced C sample code writes a file consisting of the DWORD SIMPLEBLOB size, the SIMPLEBLOB itself in blue (consisting of a 12 byte BLOBHEADER followed by a 128 byte (1024 bit) "encryption block" which in this case is not actually encrypted) and finally the 3DES encrypted ciphertext in red (02 D0 ..). A partial bin hex dump of the resultant file follows:


0000 8C 00 00 00
01 02 00 00 03 66 00 00 00 A4 00 00
0010 92 31 16 94 85 7A 67 01 79 4F 13 D0 DF 97 F1 F8
0020 D3 C1 62 CB 07 37 15 A2
00 5E 17 10 93 EB E4 22
0030 83 87 3B 49 DC B9 2D E4 E0 1A 64 72 AE DC 8E 90
0040 C8 59 A3 15 70 EE 35 EE B0 2F 91 88 80 E0 37 64
0050 4A 62 58 92 B5 C3 5D F4 1E 5B A4 38 0B 86 2D BD
0060 8D FA E7 D6 1F FD 27 8B 13 67 B9 E2 EF 35 D7 93
0070 64 51 03 70 B6 9C AC 64 60 C0 D1 65 37 04 63 52

0080 91 08 BB 31 6D BC AC 63 D4 4B 4B 46 34 3B 02 00
0090
02 D0 BE E0 7A B9 21 39 2E DD 0A 52 3B C0 1F B3
00a0 20 56 28 FE F6 EB 34 97 6B 49 CF 00 04 08 DD 9B

.........

The first highlighted 24 bytes above (92 31 ...) is the 3DES symmetric key at the start of the PKCS #1, type 2 encryption block. Note that for 3DES keys, this is the full (192 bit) key including parity bits. However, since the encryption block must be built in big-endian order, the actual 3DES symmetric key used by CryptoAPI for encryption is reversed:

BYTE[] 3deskey = {
	0xA2, 0x15, 0x37, 0x07, 0xCB, 0x62, 
	0xC1, 0xD3, 0xF8, 0xF1, 0x97, 0xDF,
	0xD0, 0x13, 0x4F, 0x79, 0x01, 0x67, 
	0x7A, 0x85, 0x94, 0x16, 0x31, 0x92 };


[Note on .NET RSA Encryption Block: Within .NET, oRSACryptoServiceProvider.Encrypt() generates a byte array representing a PKCS #1 type 2 encryption block. In .NET, the byte array is returned in big-endian format, exactly the reverse order to that formatted within a CryptoAPI SIMPLEBLOB or the encrypted buffer returned by CryptEncrypt() with RSA publickey encryption. So using the same ExponentOfOne exchange key for encryption, .NET returns:

   00 02 4E BD 53 1B 67 DC F2 69 B3 7B 58 85 81 5F
C7 DF 21 47 DD 59 45 81 28 0B AF 83 F3 2A 11 5D
53 66 EE CE 2F 8B D1 CF 90 DA 4E 23 1F A3 39 A0
67 A8 F2 02 F1 95 A4 98 56 B5 21 67 5C 46 75 08
27 C5 C2 07 D4 0C 6A 7B 4F 66 E4 F6 17 41 68 80
10 72 A0 96 9F 2C BA DD FA BD 45 AA CB 27 9F 21
99 E3 1F F0 F0 77 43 00
A2 15 37 07 CB 62 C1 D3
F8 F1 97 DF D0 13 4F 79 01 67 7A 85 94 16 31 92

where the symmetric key bytes are now at the end of the encryption block. The encryption block starts with a null byte, followed by the block type (2), then random padding data and finally the key material.]

(2) .NET Symmetric Encryption:

To reproduce exactly the same 3DES ciphertext as that created by CryptoAPI above, we use exactly the same 3deskey above (reversed as shown) and exactly the same pIV bytes (no byte reversal) to initialize a TripleDESCryptoServiceProvider encryptor instance . For the same file plaintext, the following .NET code snippet produces exactly the same ciphertext output file as the CryptoAPI sample above:

   byte[] plaintext = GetContentFileBytes();  //get file bytes to encrypt
   FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);

   byte[] tdesKey = {
	0xA2, 0x15, 0x37, 0x07, 0xCB, 0x62, 
	0xC1, 0xD3, 0xF8, 0xF1, 0x97, 0xDF,
	0xD0, 0x13, 0x4F, 0x79, 0x01, 0x67, 
	0x7A, 0x85, 0x94, 0x16, 0x31, 0x92 };

   byte[] tdesIV = {50,51,52,53,54,55,56,57} ;
   ....
   TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();          
   CryptoStream encStream = new CryptoStream(fout, tdes.CreateEncryptor(tdesKey, tdesIV), CryptoStreamMode.Write);
   encStream.Write(plaintext, 0, plaintext.Length);
   encStream.Close(); 


(3) Java 2 Symmetric Encryption:

Java 2 v 1.4+ includes an implementation of JCE API (Java Cryptography Extension) and the included "SunJCE" provider supports 3DES cipher with the common modes and padding. (By comparison, RSA encryption is NOT supported with the standard Java 2 1.4 distribution and a 3rd party provider must be added). The following code sample again produces exactly the same 3DES ciphertext file as the CryptoAPI and .NET samples above, for the same input file:

//----  Use specified 3DES key and IV from other source -------------------------
  byte[] plaintext = getContentBytes();
  byte[] tdesKeyData = {
	(byte)0xA2, (byte)0x15, (byte)0x37, (byte)0x07, (byte)0xCB, (byte)0x62, 
	(byte)0xC1, (byte)0xD3, (byte)0xF8, (byte)0xF1, (byte)0x97, (byte)0xDF,
	(byte)0xD0, (byte)0x13, (byte)0x4F, (byte)0x79, (byte)0x01, (byte)0x67, 
	(byte)0x7A, (byte)0x85, (byte)0x94, (byte)0x16, (byte)0x31, (byte)0x92 };


  byte[] myIV = {(byte)50,(byte)51,(byte)52,(byte)53,(byte)54,(byte)55,(byte)56,(byte)57};



  Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
  SecretKeySpec    myKey = new SecretKeySpec(tdesKeyData, "DESede");
  IvParameterSpec ivspec = new IvParameterSpec(myIV);

  c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
  byte[] cipherText = c3des.doFinal(plaintext);

  /* Save the 3DES ciphertext to file */
  FileOutputStream fos = new FileOutputStream("tdesJencrypted");
  fos.write(cipherText);
  fos.close();

(4) Password-derived symmetric keys:

The Example C Program: Encrypting a File also demonstrates deriving a symmetric key from a supplied password using CryptoAPI functions CryptCreateHash(), CryptHashData() and CryptDeriveKey(). The key is derived from the hash of the supplied password in a way which depends to some extent on the symmetric key algorithm requested. (In a simple case such as RC2 128 (a 16 byte key) and a SHA-1 hash, the first 16 bytes of the 20 byte SHA-1 hash of the password is the derived key. The procedure for deriving 3DES key material (24 bytes) from a 20 byte SHA-1 hash is slightly more complex.) For the same password string, exactly the same password-derived symmetric key can be derived in .NET using a method intended for CryptoAPI compatibility:

  PasswordDeriveBytes pderiver = new PasswordDeriveBytes("yourpswd", null);
  byte[] ivZeros = new byte[8];   //Not used but required.
  byte[] pbeKey = pderiver.CryptDeriveKey("TripleDES", "SHA1", 192, ivZeros);
Again, data encrypted in .NET using this password-derived key (and a supplied IV) to initialize a TripleDESCryptoServiceProvider yields identical ciphertext (same byte order) to that generated by an unmanaged CryptoAPI approach as in the C Program sample.


Michel I. Gallant
neutron@istar.ca


Comment

Zencode  (05 มีนาคม 2553)   
IP : 203.154.112.163

try {
    // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    keyGen.initialize(1024);
    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();

    // Generate a 576-bit DH key pair
    keyGen = KeyPairGenerator.getInstance("DH");
    keyGen.initialize(576);
    keypair = keyGen.genKeyPair();
    privateKey = keypair.getPrivate();
    publicKey = keypair.getPublic();

    // Generate a 1024-bit RSA key pair
    keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    keypair = keyGen.genKeyPair();
    privateKey = keypair.getPrivate();
    publicKey = keypair.getPublic();
} catch (java.security.NoSuchAlgorithmException e) {
}

 

try { // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024); KeyPair keypair = keyGen.genKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); // Generate a 576-bit DH key pair keyGen = KeyPairGenerator.getInstance("DH"); keyGen.initialize(576); keypair = keyGen.genKeyPair(); privateKey = keypair.getPrivate(); publicKey = keypair.getPublic(); // Generate a 1024-bit RSA key pair keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); keypair = keyGen.genKeyPair(); privateKey = keypair.getPrivate(); publicKey = keypair.getPublic(); } catch (java.security.NoSuchAlgorithmException e) { }

 

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();

base64 base64Encoder = new base64();
String publicExponentb64 = new String(base64Encoder.encode(rsaPublicKey.getPublicExponent().toByteArray()));
String modulusb64 = new String(base64Encoder.encode(rsaPublicKey.getModulus().toByteArray()));
RSAKeyValuexml rsaKey = new RSAKeyValuexml();
rsaKey.setModulus(modulusb64);
rsaKey.setExponent(publicExponentb64);
String rsaPublicKeyxml = rsaKey.toString();
logger.info("PUB: "+rsaPublicKeyxml);
RSAKeyValuexml.save(rsaKey "c://temp/RSAJavaPubKey.xml");


static void gen() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
PublicKey pk = kp.getPublic();
 
Rsaxml rsaxml = new Rsaxml();
rsaxml.setModulus(((RSAPublicKey)pk).getModulus());
rsaxml.setExponent(((RSAPublicKey)pk).getPublicExponent());
 
File file = new File("C:/Tmp/RSAPubKey.xml");
PrintWriter pw = new PrintWriter(file);
pw.write(rsaxml.toString());
pw.flush();
pw.close();
}
 

 



Mr.ZengCode  (05 มีนาคม 2553)   
IP : 203.154.112.163

 

 

Cryptography - Java to C# to Java RSA PKCS #1
nk href="http://forums.sun.com/rss/rssmessages.jspa?threadID=5376099" title="RSS Summary Feed" type="application/rss+xml" rel="alternate" /> nk href="http://forums.sun.com/rss/rssmessages.jspa?threadID=5376099&full=true" title="RSS Full Feed" type="application/rss+xml" rel="alternate" />
This question is answered.
 
<<   Back to Forum  |   Give us Feedback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10 Duke Stars available
This topic has 13 replies on 1 page.
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Java to C# to Java RSA PKCS #1   
Mar 25 2009 7:51 AM
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656124"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" style="color: rgb(255 255 255);" />

 
Hi

I have a Java server that generates a RSA public/private key (
KeyPairGenerator.getInstance("RSA")
) the public key is sent to a C# client and it uses it to encrypt some data to be sent back to the server.
However the decryption on the server-wise fails because it appeared that the same data generated random outputs (from C#).
Then I came across: http://blogs.msdn.com/shawnfa/archive/2006/01/05/509444.aspx

Basically RSA uses random padding on the input bytes.

In C# i am using
rsaCryptoServiceProvider.Encrypt(clearData false)
(therefore PKCS #1 v1.5)

In Java I tried to use
Cipher.getInstance("RSA/ECB/PKCS1PADDING")
but it fails with the following exception:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes.


Any idea how to fix the Java-side (or C# side)

Thx
 
tle="Dukes Earned 2204" src="http://forums.sun.com/im/platinum-star.gif" alt="" /> sabre150
Posts:22224
Registered: 24.10.97
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 8:20 AM (reply 1 of 13)  (In reply to original post )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656185"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
I suspect that you need to show more of your C# and your Java together with some sample data.
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 8:28 AM (reply 2 of 13)  (In reply to #1 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656180"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
Java Key generation:

keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();


C# RSA Creation:

RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider();
rsaCryptoServiceProvider.FromxmlString(publicKeyxml);


C# Encryption using RSA Pub Key:

public byte[] AsymmetricEncrypt(byte[] clearData)
{
return rsaCryptoServiceProvider.Encrypt(clearData false);
}


Java decipher:

Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.DECRYPT_MODE rsaPrivateKey);


Thinking out loud:

RSA cannot be used to encrypt data longer than the key size. If you're using PKCS#11 padding.
Meaning that if in C# you put false (I am not on XP) then PKCS#11 padding is used.

When I create my RSA key of length 1024 it means that RSA can decipher messages of length greater than 1024/8-11=117 bytes

In C# the encrypted data (a string like "MyPassword") generates a byte array of length 129. This is clearly > 117...
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 8:34 AM (reply 3 of 13)  (In reply to original post )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656182"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
The exception being:

"Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes"


So.. why do my C# code ciphers to 129....

Clearly missing something..

T
 
tle="Dukes Earned 2204" src="http://forums.sun.com/im/platinum-star.gif" alt="" /> sabre150
Posts:22224
Registered: 24.10.97
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 8:55 AM (reply 4 of 13)  (In reply to #2 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656245"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
ThierryTheViking wrote:

When I create my RSA key of length 1024 it means that RSA can decipher messages of length greater than 1024/8-11=117 bytes

In C# the encrypted data (a string like "MyPassword") generates a byte array of length 129. This is clearly > 117...

The problem is that it is greater than 128 not 117 since the 117 is the length before encryption. It would be interesting to look at the public key you are using.

I use RSA to encrypt/decrypt in C# and decrypt/encrypt in Java without this problem and the code you have given does not help since it shows only the basic operations you use and not the detail which will be needed to duplicate the problem.
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 9:03 AM (reply 5 of 13)  (In reply to #4 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656261"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
Hi

This is a key sample:

<RSAKeyValue>
<Modulus>AK2v6tn40jhFo/i5EVTiTIMMsQEMjPCYU7yvs2yb/1xKTHU1lBqTGI36/9sPSqiZp2tng7/zeNQ/ElGB6Ryh4zfYSI+sVyK/ZeYNqTXTLtNQCFSLECPahyF8EP3Y25mLV4XPoYxXFsXPDqdlRLr7xw3aQGuajCDK1DNG90tsvoVD</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>


BigIntegers encoded using org.apache.commons.codec.binary.base64


KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();

base64 base64Encoder = new base64();
String publicExponentb64 = new String(base64Encoder.encode(rsaPublicKey.getPublicExponent().toByteArray()));
String modulusb64 = new String(base64Encoder.encode(rsaPublicKey.getModulus().toByteArray()));
RSAKeyValuexml rsaKey = new RSAKeyValuexml();
rsaKey.setModulus(modulusb64);
rsaKey.setExponent(publicExponentb64);
String rsaPublicKeyxml = rsaKey.toString();
logger.info("PUB: "+rsaPublicKeyxml);
RSAKeyValuexml.save(rsaKey "c://temp/RSAJavaPubKey.xml");



Hope this helps.
 
tle="Dukes Earned 2204" src="http://forums.sun.com/im/platinum-star.gif" alt="" /> sabre150
Posts:22224
Registered: 24.10.97
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 9:09 AM (reply 6 of 13)  (In reply to #5 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656275"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
And on the C# side you read it using ...
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 9:10 AM (reply 7 of 13)  (In reply to #6 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656267"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
ooppsss sorry...:-)

RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider();
rsaCryptoServiceProvider.FromxmlString(publicKeyxml);


then

public byte[] AsymmetricEncrypt(byte[] clearData)
{
byte[] result = rsaCryptoServiceProvider.Encrypt(clearData false);
log("AsymmetricEncrypt of data of length: " + clearData.Length +" result length: " + result.Length);
return result;
}
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 9:13 AM (reply 8 of 13)  (In reply to #7 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656268"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
var streamReader = new StreamReader(@"C:\TEMP\RSAJavaPubKey.xml" encoding);
string rsaPubKey = streamReader.ReadToEnd();
streamReader.Close();
 
tle="Dukes Earned 2204" src="http://forums.sun.com/im/platinum-star.gif" alt="" /> sabre150
Posts:22224
Registered: 24.10.97
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 9:24 AM (reply 9 of 13)  (In reply to #7 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656293"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
I'm struggling to help here since I don't have access to enough of your code to test anything. For example you have a utility class RSAKeyValuexml which I assume you wrote (since I can't find it though Google) but I don't know what it does. I do wonder why you did not use X509 to transfer the public key.

When I have problems like this I create stand alone test harnesses that allows me to see exactly what is going on. Both the C# and Java parts to this should be no more than about 20 lines of code but since I can only see a small fragment of your code my chance of creating a test harness that duplicates the code you are using is just about zero. I suspect that you have to create the test harness.
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 9:27 AM (reply 10 of 13)  (In reply to #9 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656274"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
I understand.
RSAKeyValuexml is nothing more that a class that generates the xml that looks like:

<RSAKeyValue><Modulus>AKdEmEQy8JdG8fcdsw50fsX8frS/hx4fX7Cb/Gz1IDaj4kYMmRBi87yP4VWY/1koJZiDUzM6KswORH3Uy3n6ZVsPPelVJIylBmli0FHtJha9nB5notDSmR9lMSf1CLoHZqA3k9fbJObC5803XqvViDdcGpvcBCuEa7RZe4uSZJ0h</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>

Which is then imported via the FromxmlString method.

It does work no C# exception here.

How would you create/use a X509 certificate from Java and C#?
 
tle="Dukes Earned 2204" src="http://forums.sun.com/im/platinum-star.gif" alt="" /> sabre150
Posts:22224
Registered: 24.10.97
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 9:36 AM (reply 11 of 13)  (In reply to #10 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656322"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
The getEncoded() method on the public key is an X509 certificate. The C# libraries for handling x509 - http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.aspx .
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 25 2009 1:45 PM (reply 12 of 13)  (In reply to #11 )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10656626"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
Still no luck:

Java:

public class Main {
/**
* @param args the command line arguments
*/

public static void main(String[] args) throws Exception {
read();
}

static void read() throws Exception {
File file = new File("C:/Tmp/Crypted.properties");
Properties p = new Properties();
p.load(new FileInputStream(file));
String data = p.getProperty("data");
log("Data: " + data);
log("Data: " + data.length());
 
byte[] datum = new base64().decode(data.getBytes());
log("Datum size: " + datum.length);
}
 
static void gen() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
PublicKey pk = kp.getPublic();
 
Rsaxml rsaxml = new Rsaxml();
rsaxml.setModulus(((RSAPublicKey)pk).getModulus());
rsaxml.setExponent(((RSAPublicKey)pk).getPublicExponent());
 
File file = new File("C:/Tmp/RSAPubKey.xml");
PrintWriter pw = new PrintWriter(file);
pw.write(rsaxml.toString());
pw.flush();
pw.close();
}
 
/**
*
* @param o
*/

static void log(object o) {
System.out.println(o);
}
}


and

C#

static void Main(string[] args)
{
log("*** CRYPTO CS ***");
 
RSACryptoServiceProvider rsaCryptoProvider = new RSACryptoServiceProvider();
 
StreamReader sr = new StreamReader(@"C:\Tmp\RSAPubKey.xml");
string rsaxml = sr.ReadToEnd();
sr.Close();
log(rsaxml);
 
rsaCryptoProvider.FromxmlString(rsaxml);
log("rsaCryptoProvider: " + rsaCryptoProvider.SignatureAlgorithm);
 
string plain = "MyPassword";
byte[] crypted = rsaCryptoProvider.Encrypt(Encoding.Default.GetBytes(plain) false);
 
log("Crypted data length: " + crypted.Length);
 
string cryptedB64 = "data="+Convert.Tobase64String(crypted);
StreamWriter sw = new StreamWriter(@"C:\Tmp\Crypted.properties");
sw.Write(cryptedB64);
sw.Close();
}


Could this be related to the encoding used?
 
tle="Dukes Earned 0" src="http://forums.sun.com/im/bronze-star.gif" alt="" /> ThierryTheViking
Posts:27
Registered: 3/29/07
Re: Java to C# to Java RSA PKCS #1   
Mar 26 2009 4:00 AM (reply 13 of 13)  (In reply to original post )
 
tle="Click to email this message" href="http://forums.sun.com/emailmessage%21default.jspa?messageID=10657211"> Click to email this message

mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value="Reply »" class="buttonblue" />

 
Probleme solved.
Ok I think that all my issues where related to the encoding of the xml key to be read by C#. In the end I decided to go a complete different route: instead of doing the public key generation in Java I have decided to use keytool export the public key as a X509 certificate then import it into C#. It works like a charm.

Follow this procedure:

1) Use keytool to generate the public key specifying for example keytool -genkeypair etc... -keyalg RSA -keysize 1024
2) Export the key into a X509 certificate: keytool -exportcert etc.. -rfc -file itsc.cer

If this works on Windows you can double-click on itsc.cer and you will see a nice window with the certificate information

In C#:

1) Import the certificate:

var streamReader = new StreamReader(@".....\itsc.cer");
string x509Str = streamReader.ReadToEnd();
streamReader.Close();
var x509Certificate = new X509Certificate2(Encoding.UTF8.GetBytes(x509Str));
RSACryptoServiceProvider rsaCryptoServiceProvider = (RSACryptoServiceProvider)x509Certificate.PublicKey.Key;


"That's it."

Back to Java.

What you need to do is to extract by code the private key from the keystore:

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(keyStorePath) "your password".toCharArray());
Key key = keyStore.getKey("your alias" "your password".toCharArray());


Then you can decrypt what has been sent by the C# client

T
 
This topic has 13 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
 
focus="if( this.value==this.defaultValue ) this.value='';" size="6" class="medium" name="qt" id="f7text1" />    mouseout="this.style.color='#FFF';" onmouseover="this.style.color='#fbe249';" value=" » " class="hotbutton" />
 
ript type="text/javascript">ript> ript src="http://ads.sun.com/ads/www/delivery/ajs.php?zoneid=585&cb=81267680883&charset=ISO-8859-1&loc=http%3A//forums.sun.com/thread.jspa%3FthreadID%3D5376099&referer=http%3A//www.google.co.th/url%3Fsa%3Dt%26source%3Dweb%26ct%3Dres%26cd%3D8%26ved%3D0CEIQFjAH%26url%3Dhttp%253A%252F%252Fforums.sun.com%252Fthread.jspa%253FthreadID%253D5376099%26rct%3Dj%26q%3Dc%2523+rsa+generate+key+pair+for+java%26ei%3D2diQS-XEJZO3rAfLqL2LCw%26usg%3DAFQjCNEwg-_eJXWBLmRv5n0A4dfQu0IceA%26sig2%3D6V5MFTznOxn7p8tUnfmMAg" type="text/javascript">ript> ript><a href='http://ads.sun.com/ads/www/delivery/ck.php?n=a4223322&amp;cb=555' target='_blank'><img src='http://ads.sun.com/ads/www/delivery/avw.php?zoneid=585&amp;cb=555&amp;n=a4223322' border='0' alt='' /></a>ript>
 
Forums Statistics

About Sun forums
  • Oracle Forums is a large collection of user generated discussions. It is here to help you ask questions find answers and participate in discussions.

    Check out our guide on Getting started with Oracle Forums for a full walkthrough of how to best leverage the benefits of this community.

ript src="http://forums.sun.com/s_code_remote.js" language="javascript" type="text/javascript">ript> ript src="http://www-cdn.sun.com/share/metrics/metrics_group1.js" type="text/javascript">ript>
 
Powered by Jive Forums





Name
Comment
Security CodeCAPTCHA Image

easy tracking
avis car rental discount code

This page took 0.083091 seconds to load.