C # interworking with Java Rsa encryption and decryption,

Source: Internet
Author: User

C # interworking with Java Rsa encryption and decryption,

It has been more than 10 years since the establishment of Rsa encryption standards. in the past two days, I have read the rsa encryption article, basically speaking.. net and java. because the project is useful, it took a little time to understand rsa encryption. It was found that both java and C # implemented standard encryption for rsa, and the standard was implemented, if you cannot connect, you cannot talk about it. I wrote a piece of java code specially today and tried it. I found that it is all right.

 

Key Description: C #(.. net. I do not understand the blob format. I only know what api is used for Microsoft in the document. The following describes the parameter format.

RSAParameters Field

Contains

Corresponding PKCS #1 Field

D

D. Private Key Index

PrivateExponent

DP

D mod (p-1)

Exponent1

DQ

D mod (q-1)

Exponent2

Exponent

E. Public Key Index

PublicExponent

InverseQ

(InverseQ) (q) = 1 mod p

Coefficient

Modulus

N

Modulus

P

P

Prime1

Q

Q

Prime2

 

RSA Algorithm

To generate a key pair, you can create two large prime numbers named p and q. These two numbers are multiplied and the result is called n. Because p and q are both prime numbers, therefore, all factors of n are 1, p, q, and n;

If only the number less than n is considered, the number of the numbers that are equal to n is equal to (p-1) (q-1 );

Now, select a number e, which corresponds to the calculated value as the reciprocal number; then the public key is represented as {e, n };

To create a private key, you must calculate d, which is a number that satisfies (d) (e) mod n = 1. According to Euclidean algorithm, the private key is {d, n };

Encryption from plain text m to Password text c is defined as c = (m ^ e) mod n; decryption is defined as m = (c ^ d) mod n;

 

In short, we can get the appropriate key description from the. net rsa. As for java, I think it is also possible, and usually the key should be placed in the key container.

 

Next we use. net to generate an rsa key and output it in hexadecimal format (new RSACryptoServiceProvider, export the key)

 

D: 2FE7479CF4CFEE63218C44D763C3E552DC5FBC94A31F944B88AE8E58F0ED16874B8BED35307B143F413761B2ECFFC95F48DF0D0A29FC155C0B968EFE9FFF36E7DP: 6777B761BC29637622FC63682243BB2E05CCFC6FF710ADE1DCE6B0C843B17C4FDQ: 68771CCDA40F0DA0B504C438BB03F7DF30F77364094D475E70270D148260D247Exponent: 010001InverseQ: 5665AB47697008CC2CECB544B582B9C50628281C400846C1E736629B03FE5C85Modulus: B3F276C8EDF515FD3248CCF4163480B9F77443A666522D66B89411EC6DFE11DEA917A97C977750EE777DACBD4D2C11BC363FDC110E5CCA0A1361D51AFA4A7ADDP: ECC60A01B1BDCBA1C5422D8A0A34FC0E46727DB4ED5089E54C356F052E0AB573Q: C28F233948483D0CD0E3FA7B5D2955F2B15E831B38876FB0E7180D873EDF7A6F


 

 

To facilitate writing. net code, paste the blob key here

0702000000A40000525341320002000001000100DD7A4AFA1AD561130ACA5C0E11DC3F36BC112C4DBDAC7D77EE5077977CA917A9DE11FE6DEC1194B8662D5266A64374F7B9803416F4CC4832FD15F5EDC876F2B373B50A2E056F354CE58950EDB47D72460EFC340A8A2D42C5A1CBBDB1010AC6EC6F7ADF3E870D18E7B06F87381B835EB1F255295D7BFAE3D00C3D484839238FC24F7CB143C8B0E6DCE1AD10F76FFCCC052EBB43226863FC22766329BC61B7776747D26082140D27705E474D096473F730DFF703BB38C404B5A00D0FA4CD1C7768855CFE039B6236E7C14608401C282806C5B982B544B5EC2CCC08706947AB6556E736FF9FFE8E960B5C15FC290A0DDF485FC9FFECB26137413F147B3035ED8B4B8716EDF0588EAE884B941FA394BC5FDC52E5C363D7448C2163EECFF49C47E72F

 

 

Because it is a private key, it can be encrypted and decrypted at the same time. The C # code below is relatively simple.

 

using System;    using System.Security.Cryptography;    class Program    {        public static void Main(string[] args)        {                        byte[] plainText = new byte[]{0,1,2,3,4,5};            byte[] cipherText;            byte[] key = String2Bytes("0702000000A40000525341328001000001000100D3D10816051881319774576B67B1D24F3AA303471A4402AB625208EC1CB04D508AF2098227C5EE185890ECB83E6971C12BDCF4F8AB0FD729167C815D3404C1AD1C0628E3544C89E9F9044A6869447310C72D7CDEB5E3582AB28BCC5069D60CD4AB5A1BB8C754AEB544FA65FB990ADB68F5AA37D7AC2CCDBF19058A2A4CF18FC29577D184E75EFD0ABEC1263893262F40C89AB2831B20B52B477770BA95FA02A71339911EBBF8630AD1AEECC205888440037D580B18AEF11FC5F35EB74E434E5A9302823BF795A34DADDFE0C6D55BC7997E667ADBE511BA06");            using(var rsa = new RSACryptoServiceProvider())            {                rsa.ImportCspBlob(key);                Console.WriteLine("OAEP:");                Console.WriteLine(Bytes2String(rsa.Encrypt(plainText, true)));                Console.WriteLine("PCSK1-v1_5:");                Console.WriteLine(Bytes2String(rsa.Encrypt(plainText, false)));            }            Console.Write("Press any key to continue . . . ");            Console.ReadKey(true);        }                        const string pattern = @"[^0-9a-fA-F]+";        static byte[] String2Bytes(string str)        {            str = System.Text.RegularExpressions.Regex.Replace(str, pattern, "");            if (str == string.Empty)                return null;            byte[] data = new byte[str.Length / 2];                        for (int i = 0; i < data.Length; ++i)                data[i] = byte.Parse(str.Substring(2 * i, 2), System.Globalization.NumberStyles.HexNumber);            return data;        }        static string Bytes2String(byte[] data)        {            System.Text.StringBuilder builder = new System.Text.StringBuilder();            foreach (var  element in data) {                builder.AppendFormat("{0:X2}",element);            }            return builder.ToString();        }    }

Output after running (rsa encryption, ciphertext is not necessarily the same every time ):

OAEP:
Bytes
PCSK1-v1_5:
Bytes

Now we have the ciphertext. As for the. net ciphertext after decryption, I am not interested in it. It is definitely enough.

 

Below we will write the java decryption Section

Package rsatest; import java. math. bigInteger; import java. security. keyFactory; import java. security. privateKey; import java. security. publicKey; import java. security. spec. rsw.vatekeyspec; import java. security. spec. RSAPublicKeySpec; import javax. crypto. cipher; public class RsaTest {public static void main (String [] args) throws Exception {// 0 is added before, and the symbol bit is 0, non-negative BigInteger n = new BigInteger ("B3F276C8EDF515FD Keys ", 16); BigInteger e = new BigInteger (" 010001 ", 16); BigInteger d = new BigInteger (" keys ", 16); RSAPublicKeySpec keySpec = new RSAPublicKeySpec (n, e); PublicKey pub LicKey = KeyFactory. getInstance ("RSA "). generatePublic (keySpec); rsrentvatekeyspec prvKeySpec = new rsrentvatekeyspec (n, d); PrivateKey privateKey = KeyFactory. getInstance ("RSA "). generatePrivate (prvKeySpec); // now the key is ready. Put the preceding ciphertext here to decrypt byte [] oaepCiphertext = Hex2Bytes ("encrypt ");/ /Decrypt the encrypted data Cipher cipher = Cipher. getInstance ("RSA/ECB/OAEPPADDING"); cipher. init (Cipher. DECRYPT_MODE, privateKey); byte [] plaintext = cipher. doFinal (oaepCiphertext); System. out. println (Bytes2Hex (plaintext); // decrypts the Data byte [] ciphertext = Hex2Bytes ("encrypted"); ciph Er = Cipher. getInstance ("RSA"); cipher. init (Cipher. DECRYPT_MODE, privateKey); plaintext = cipher. doFinal (ciphertext); System. out. println (Bytes2Hex (plaintext);} public static byte [] Hex2Bytes (String hexStr) {if (hexStr. length () % 2! = 0) {hexStr = "0" + hexStr;} byte [] bytes = new byte [hexStr. length ()/2]; for (int I = 0; I <bytes. length; ++ I) {bytes [I] = (byte) Integer. parseUnsignedInt (hexStr. substring (I * 2, I * 2 + 2), 16);} return bytes;} public static String Bytes2Hex (byte [] bytes) {StringBuilder builder = new StringBuilder (); for (byte B: bytes) {builder. append (String. format ("% 02X", B);} return builder. toString ();}}

Output after running the program:

000102030405
000102030405

It is the same as we expected.

 

We use java to encrypt plaintext and code snippets.

// plaintext {0,1,2,3,4,5}        cipher = Cipher.getInstance("RSA/ECB/OAEPPADDING");        cipher.init(Cipher.ENCRYPT_MODE, publicKey);        oaepCiphertext = cipher.doFinal(plaintext);        System.out.println("OAEP:");        System.out.println(Bytes2Hex(oaepCiphertext));                cipher = Cipher.getInstance("RSA");        cipher.init(Cipher.ENCRYPT_MODE, publicKey);        ciphertext = cipher.doFinal(plaintext);        System.out.println("PCSK1-v1_5:");        System.out.println(Bytes2Hex(ciphertext));

Corresponding output (rsa encryption, ciphertext is not necessarily the same every time ):

OAEP:
Bytes
PCSK1-v1_5:
Bytes

 

Next, use C # to decrypt the data and code snippets.

// Use the previous rsa object // OAEPcipherText = String2Bytes ("secret"); Console. writeLine (Bytes2String (rsa. decrypt (cipherText, true); // PCSK1-v1_5cipherText = String2Bytes ("encrypted"); Console. writeLine (Bytes2String (rsa. decrypt (cipherText, false )));

Corresponding output:

000102030405
000102030405

Decryption is successful.

 

The problem may be that {e, n} or {d, n} is known how to generate the key used by. net.


C :\

Yes

Refer to this to clean up the C drive:
1. Disable System Restoration: My computer properties/System Restoration/disable System Restoration on all disks, but I will not be able to use system restoration in the future!
2. Disable System sleep: Control Panel/Power Supply/sleep/remove the check before starting system sleep
3. move the virtual memory, my computer properties/advanced/performance/settings/advanced/change/select the C disk, that is, the system disk, select the no-score page, and then set the virtual memory to its disk, A disk with more disk space remaining, such as D, E, and F. set to 1.5 ~ of memory ~ 2.5 times. The size can be set to the same!
5. Clear temporary IE folders, internet Options, and delete temporary and offline files.
6. delete system logs and program logs, my computer/control panel/management tools/Computer Management/Event Viewer/application, right-click/clear events, and clear system logs in sequence
7. Clear system cache: 2000 all files in the system: C: \ WINNT \ system32 \ dllcache
The XP system is: C: \ windows \ system32 \ dllcache all files under the system cache (open my computer/tool/file and Folder Options/hide the protected system file hook off to hide all files on the hook) ). You can also run the sfc.exe/purgecache command to automatically delete the file.
8. Clear the recycle bin
9. delete the files under c: \ windows \ SoftwareDistribution \ Download (the files downloaded when the system is updated are useless if you have installed the updates)
10. Delete all directories under c: \ windows \ RegisteredPackages
11. Delete all Files under C: \ WINDOWS \ Downloaded Program Files
12. view the hidden files that are known to be protected by the system in my computer folder option, and check all the files.
13. Delete c: \ windows \ All files with $8882305 $ (backup files after system update)

Zhidao.baidu.com/question/11035955.html
Zhidao.baidu.com/question/12223613.html
Zhidao.baidu.com/question/14874715.html
... The remaining full text>

C :\

Yes

Refer to this to clean up the C drive:
1. Disable System Restoration: My computer properties/System Restoration/disable System Restoration on all disks, but I will not be able to use system restoration in the future!
2. Disable System sleep: Control Panel/Power Supply/sleep/remove the check before starting system sleep
3. move the virtual memory, my computer properties/advanced/performance/settings/advanced/change/select the C disk, that is, the system disk, select the no-score page, and then set the virtual memory to its disk, A disk with more disk space remaining, such as D, E, and F. set to 1.5 ~ of memory ~ 2.5 times. The size can be set to the same!
5. Clear temporary IE folders, internet Options, and delete temporary and offline files.
6. delete system logs and program logs, my computer/control panel/management tools/Computer Management/Event Viewer/application, right-click/clear events, and clear system logs in sequence
7. Clear system cache: 2000 all files in the system: C: \ WINNT \ system32 \ dllcache
The XP system is: C: \ windows \ system32 \ dllcache all files under the system cache (open my computer/tool/file and Folder Options/hide the protected system file hook off to hide all files on the hook) ). You can also run the sfc.exe/purgecache command to automatically delete the file.
8. Clear the recycle bin
9. delete the files under c: \ windows \ SoftwareDistribution \ Download (the files downloaded when the system is updated are useless if you have installed the updates)
10. Delete all directories under c: \ windows \ RegisteredPackages
11. Delete all Files under C: \ WINDOWS \ Downloaded Program Files
12. view the hidden files that are known to be protected by the system in my computer folder option, and check all the files.
13. Delete c: \ windows \ All files with $8882305 $ (backup files after system update)

Zhidao.baidu.com/question/11035955.html
Zhidao.baidu.com/question/12223613.html
Zhidao.baidu.com/question/14874715.html
... The remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.