Example of data encryption and platform independence

Source: Internet
Author: User
Tags openssl library
In the world of computer software development, there are many programming languages, and data may have different forms of representation in different languages, but data processing may, or is essentially the same; for example, the calculation process of data in an algorithm is the same. Here, I use encryption and decryption as an example.

In C ++, I used the OpenSSL library to generate the RSA public/private key pair and the session key used for DES encryption, and write the three and the encrypted results into the file for use in the Java environment.

In the C ++ program, I use the public key to encrypt the session key of DES, and then use the private key in Java to decrypt the session key. In the calculation result, I have not implemented Code Conversion in other aspects, that is, DER encoding based on the initial format of the key, and DER encoding for the mathematical computation results.

In the Java program, I obtained the key and encryption result from several files stored previously for decryption. I used BC's JCE, that is, the bcprov-jdk14-119.jar, and before using it, I need to install this JCE first:

Suppose JDK: jdk1.4 \ JRE \
Put the BC package to ext: jdk1.4 \ JRE \ Lib \ ext under JRE.
Modify the jdk1.4 \ JRE \ Lib \ SECURITY \ Java. Security:
#
# List of providers and their preference orders (see above ):
#
Security. provider.1 = sun. Security. provider. Sun
Security. provider.2 = com.sun.net. SSL. Internal. SSL. Provider
Security. provider.3 = com. Sun. rsajca. Provider
Security. provider.4 = com. Sun. crypto. provider. sunjce
Security. provider.5 = sun. Security. jgss. sunprovider

Security. provider.6 = org. bouncycastle. JCE. provider. bouncycastleprovider

========================================================== ====================================

C ++ program source code:

# Include
# Include
# Include
// # DEFINE _ rsa_key_pair_generate _ // whether to generate the key. You only need to enable this macro at the first run.

# DEFINE _ rsa_key_pair_tofile _ // whether the key pair needs to be written into the file

# Define max_rsa_key_length 512 // the maximum length of the key is 512 bytes.

# Define pubkey_encrypt
# Define prikey_decrypt

# Pragma comment (Lib, "../lib/libeay32.lib ")
Static const char * public_key_file = "pubkey. Key ";
Static const char * private_key_file = "prikey. Key ";

Int rsakeypairgen (void)
{
RSA * RSA = NULL;

# Ifdef _ rsa_key_pair_generate _
// Generate an RSA key pair:
RSA = rsa_new ();
RSA = rsa_generate_key (1024, 0x10001, null, null );
# Endif
 
// Write the key pair to the file and read it from the file later
# Ifdef _ rsa_key_pair_tofile _
Unsigned char ucpubkey [max_rsa_key_length] = {0}, ucprikey [max_rsa_key_length] = {0 };
Int Len = i2d_rsapublickey (RSA, null );
Unsigned char * PT = ucpubkey;
Len = i2d_rsapublickey (RSA, & pt );
 
File * fpubkey = NULL;
Fpubkey = fopen (public_key_file, "WB ");
If (fpubkey = NULL)
{
Cout <"fopen pubkey. Key failed! "<Endl;
Return 0x01;
}
Fwrite (ucpubkey, 1, Len, fpubkey );
Fclose (fpubkey );
 
Len = i2d_rs1_vatekey (RSA, null );
Unsigned char * pt2 = ucprikey;
Len = i2d_rs1_vatekey (RSA, & pt2 );
File * fprikey = NULL;
Fprikey = fopen (private_key_file, "WB ");
If (fprikey = NULL)
{
Cout <"fopen prikey. Key failed! "<Endl;
Return 0x02;
}
Fwrite (ucprikey, 1, Len, fprikey );
Fclose (fprikey );
# Endif
 
If (RSA! = NULL)
{
Rsa_free (RSA );
RSA = NULL;
}
Return 0;
}

// Read the data of the private key from the file and obtain the RSA private key:
Int getprikey (unsigned char * pucprikeydata, unsigned long keydatalen, RSA ** prirsa)
{
Unsigned char * PT = pucprikeydata;
* Prirsa = d2i_rs1_vatekey (null, & PT, keydatalen );
If (prirsa = NULL)
{
Cout <"prirsa = NULL! "<Endl;
Return 0x22;
}
Return 0;
}

// Obtain the RSA public key:
Int getpubkey (unsigned char * pucpubkeydata, unsigned long keydatalen, RSA ** pubrsa)
{
Unsigned char * PT = pucpubkeydata;
* Pubrsa = d2i_rsapublickey (null, & PT, keydatalen );
If (pubrsa = NULL)
{
Cout <"pubrsa = NULL! "<Endl;
Return 0x31;
}
Return 0;
}

// Public key encryption session key:
Int encsessionkeybyrsapubkey (RSA * RSA, unsigned char * uckey, unsigned long ulkeylen,
Unsigned char * outdata, unsigned long * puloutlen)
{
Return (* puloutlen = rsa_public_encrypt (ulkeylen, uckey, outdata, RSA, 1 ));
}

// Private Key decryption session key:
Int decsessionkeybyrs1_key (RSA * RSA, unsigned char * indata, unsigned long uldatalen,
Unsigned char * uckey, unsigned long * pulkeylen)
{
Return (* pulkeylen = rsa_private_decrypt (uldatalen, indata, uckey, RSA, 1 ));
}

Int main (INT argc, char * argv [])
{
Unsigned char uckey [8] = {0x01, 0x03, 0x99, 0x4 ,\
0x80, 0x65, 0x34, 0x08 };
Unsigned char ucencryptedkey [512] = {0}, ucdecryptedkey [512] = {0 };
Unsigned long encrypted_len = 0, decrypted_len = 0;
 
 
# Ifdef _ rsa_key_pair_generate _
Rsakeypairgen ();
# Endif

// Obtain the public key:
Unsigned char ucpubkey [max_rsa_key_length] = {0 };
 
File * fpubkey = NULL;
Fpubkey = fopen (public_key_file, "rb ");
If (fpubkey = NULL)
{
Cout <"fopen pubkey. Key failed! "<Endl;
Return 0x03;
}
Fseek (fpubkey, 0, seek_end );
Int len_pk = ftell (fpubkey );
Fseek (fpubkey, 0, seek_set );
Fread (ucpubkey, 1, len_pk, fpubkey );
Fclose (fpubkey );

# Ifdef pubkey_encrypt
RSA * prsapubkey = NULL;
Prsapubkey = rsa_new ();
 
Getpubkey (ucpubkey, len_pk, & prsapubkey );
// Public key encryption:
Encsessionkeybyrsapubkey (prsapubkey, uckey, sizeof (uckey), ucencryptedkey, & encrypted_len );
// Write to file:
File * fp = NULL;
Fp = fopen ("uckey. Data", "WB ");
Fwrite (ucencryptedkey, 1, encrypted_len, FP );
Fclose (FP );

If (prsapubkey! = NULL)
{
Rsa_free (prsapubkey); prsapubkey = NULL;
}
# Endif
 
// Obtain the private key:
Unsigned char ucprikey [max_rsa_key_length] = {0 };
 
File * fprikey = NULL;
Fprikey = fopen (private_key_file, "rb ");
If (fprikey = NULL)
{
Cout <"fopen prikey. Key failed! "<Endl;
Return 0x02;
}
Fseek (fprikey, 0, seek_end );
Int len_sk = ftell (fprikey );
Fseek (fprikey, 0, seek_set );
Fread (ucprikey, 1, len_sk, fprikey );
Fclose (fprikey );

# Ifdef prikey_decrypt
RSA * prsaprikey = NULL;
Prsaprikey = rsa_new ();
 
Getprikey (ucprikey, len_sk, & prsaprikey );
// Private Key decryption:
File * FP1 = NULL;
FP1 = fopen ("uckey. Data", "rb ");
Int Len = ftell (FP1 );
Fseek (FP1, 0, seek_set );
Fread (ucprikey, 1, len_sk, FP1 );
Fclose (FP1 );
Decsessionkeybyrs1_key (prsaprikey, ucencryptedkey, encrypted_len, ucdecryptedkey, & decrypted_len );
If (prsaprikey! = NULL)
{
Rsa_free (prsaprikey); prsaprikey = NULL;
}

// Data comparison:
If (0 = memcmp (uckey, ucdecryptedkey, decrypted_len ))
{
Cout <"OK! "<Endl;
}
Else
{
Cout <"failed! "<Endl;
}
# Endif
 
Return 0;
}

========================================================== ====================================

Java program source code:

========================================================== ====================================

Package jrsaencrypt;

Import java. Io .*;
Import java. Security .*;
Import java. Security. spec .*;
Import java. Security. publickey;
Import java. Security. privatekey;
Import java. Security. keyfactory;
Import javax. crypto. Cipher .*;

/**
*

Title:

*

Description:

*

Copyright: Copyright (c) 2005

*

Company:

* @ Author not attributable
* @ Version 1.0
*/

Public class rsakeygen {

Public rsakeygen (){
}
/**
* Generate an RSA key pair
* @ Return
*/
Int generatersakeypair (){
// Generate an RSA key pair
Try {
Keypairgenerator keygen = keypairgenerator. getinstance ("RSA ");
Keygen. initialize (1024 );
Keypair pair = keygen. generatekeypair ();
System. Out. println (pair. getpublic (). getformat ());
System. Out. println (pair. getpublic (). getalgorithm ());
System. Out. println ("\ NRSA Public Key :");
Byte [] bpubkey = pair. getpublic (). getencoded ();
System. Out. println (bpubkey. Length );
For (INT I = 0; I <bpubkey. length; I ++ ){
System. Out. Print (bpubkey [I] + "");
}
System. Out. println ("\ NRSA private key :");
Byte [] bprikey = pair. getprivate (). getencoded ();
System. Out. println (bprikey. Length );
For (INT I = 0; I <bprikey. length; I ++ ){
System. Out. Print (bprikey [I] + "");
}

}
Catch (exception e ){
E. printstacktrace ();
}
Return 0;
}
/**
* Obtain the public key from the Public Key Data
* @ Param bpubkeyinput
* @ Return
*/
Publickey getrsapubkey (byte [] bpubkeyinput ){
Byte [] bx509pubkeyheader = {
48,-127,-97, 48, 13, 6, 9, 42,-122, 72,-122,-9, 13, 1, 1, 1, 5, 0,
3,-127,-115, 0 };
Try {
Byte [] bpubkey = new byte [bpubkeyinput. Length + bx509pubkeyheader. Length];
System. arraycopy (bx509pubkeyheader, 0, bpubkey, 0,
Bx509pubkeyheader. Length );
System. arraycopy (bpubkeyinput, 0, bpubkey, bx509pubkeyheader. length,
Bpubkeyinput. Length );

X509encodedkeyspec rsakeyspec = new x509encodedkeyspec (bpubkey );
Keyfactory = keyfactory. getinstance ("RSA ");
Rsapubkey = keyfactory. generatepublic (rsakeyspec );
}
Catch (exception e ){
E. printstacktrace ();
}

Return rsapubkey;
}

/**
* Obtain the private key from the private key data
* @ Param bprikeyinput
* @ Return
*/
Privatekey getrs1_key (byte [] bprikeyinput ){
Byte [] bx509prikeyheader = {
48,-126, 2,117, 2, 1, 0, 48, 13, 6, 9, 42,
-122, 72,-122,-9, 13, 1, 1, 5, 0, 4,-126, 2, 95 };
Try {
Byte [] bprikey = new byte [bx509prikeyheader. Length + bprikeyinput. Length];
System. arraycopy (bx509prikeyheader, 0, bprikey, 0,
Bx509prikeyheader. Length );
System. arraycopy (bprikeyinput, 0, bprikey, bx509prikeyheader. length,
Bprikeyinput. Length );

Pkcs8encodedkeyspec rsakeyspec = new pkcs8encodedkeyspec (bprikey );
Keyfactory = keyfactory. getinstance ("RSA ");
Rs1_key = keyfactory. generateprivate (rsakeyspec );
}
Catch (exception e ){
E. printstacktrace ();
}
Return rs1_key;
}

/**
* Getting data from a file
* @ Param strfilename
* @ Param bfbytes
* @ Return
*/
Int getbytesbyfilename (string strfilename, byte [] bfbytes ){
Int fsize = 0;
Try {
Fileinputstream fin = new fileinputstream (strfilename );
Fsize = fin. Available ();
System. Out. Print ("file's size :");
System. Out. println (fsize );
Fsize = fin. Read (bfbytes );
Fin. Close ();
}
Catch (exception e ){
E. printstacktrace ();
}
Return fsize;
}

/**
* Public Key Encryption
* @ Param bkey
* @ Return
*/
Byte [] rsapubkeyencrypt (byte [] bkey ){
Try {
// Provider prvd = Security. getprovider ("bouncycastle ");
Javax. crypto. Cipher rsapkenc = javax. crypto. Cipher. getinstance (
"RSA/ECB/pkcs1padding ");
Rsapkenc. INIT (javax. crypto. Cipher. encrypt_mode, rsapubkey );
Bencrypteddata = rsapkenc. dofinal (bkey );
}
Catch (exception e ){
E. printstacktrace ();
}
Return bencrypteddata;
}

/**
* Private Key decryption
* @ Param bencryptedkey
* @ Return
*/
Byte [] rs1_keydecrypt (byte [] bencryptedkey ){
Try {
Javax. crypto. Cipher rsaskdec = javax. crypto. Cipher. getinstance (
"RSA/ECB/pkcs1padding ");
Rsaskdec. INIT (javax. crypto. Cipher. decrypt_mode, rs1_key );
Byte [] bdecrypt = rsaskdec. dofinal (bencryptedkey );
// System. Out. println ("RSA decrypted result [before clean]:");
// For (INT I = 0; I <bdecrypt. length; I ++ ){
// System. Out. Print (bdecrypt [I] + "");
//}
// System. Out. println ();

Int I = 0;
// For (I = bdecrypt. length; I> 1; I --){
// If (bdecrypt [I-1] = 0 ){
// System. Out. println ("I =" + I );
// Break;
//}
///} //
Bdecrypteddata = new byte [bdecrypt. Length-I];
System. arraycopy (bdecrypt, I, bdecrypteddata, 0, bdecrypt. Length-I );
}
Catch (exception e ){
E. printstacktrace ();
}
Return bdecrypteddata;
}

Public static void main (string [] ARGs ){
Rsakeygen rsakeygen1 = new rsakeygen ();

// Rsakeygen1.generatersakeypair ();

// Byte [] bpubkey = new byte [1, 140];
// Int Len = rsakeygen1.getbytesbyfilename ("pubkey. Key", bpubkey );
// Rsakeygen1.getrsapubkey (bpubkey );

Byte [] bprikey = new byte [1, 607];
Int len2 = rsakeygen1.getbytesbyfilename ("prikey. Key", bprikey );
Rsakeygen1.getrs1_key (bprikey );
// Byte [] bkey = {
// 1, 2, 3, 4, 5, 6, 7, 8 };
/// Encrypt:
// Byte [] benckey = rsakeygen1.rsapubkeyencrypt (bkey );
// System. Out. println ("RSA encrypted Result :");
// For (INT I = 0; I <benckey. length; I ++ ){
// System. Out. Print (benckey [I] + "");
//}
// System. Out. println ();

Byte [] benckey = new byte [1, 128];
Int len0 = rsakeygen1.getbytesbyfilename ("uckey. Data", benckey );
Byte [] bdeckey = rsakeygen1.rs1_keydecrypt (benckey );
System. Out. println ("RSA decrypted Result :");
For (INT I = 0; I <bdeckey. length; I ++ ){
System. Out. Print (bdeckey [I] + "");
}
System. Out. println ();
}

Publickey rsapubkey;
Privatekey rs1_key;
Byte [] bencrypteddata;
Byte [] bdecrypteddata;
}

========================================================== ====================================

Here, I simply write a small part of encryption and decryption. In more scenarios or different algorithms, you only need to specify the same encryption mode and completion mode for the algorithms in different language environments, ensure that the byte sequence is the same, and the key generation method is the same as the encoding. Therefore, no matter which development language, the data processing result should be the same.

However, for different hardware platforms, there may be some differences. Note this because I have encountered such a problem, if the stack of bytes is different, the results of an encryption algorithm are different. This bug is hard to find out, because the difference is only one byte, that is, the CPU may have different bytes, I hope this problem won't happen to you!

The source code of the above two parts is tested on vc6 and jb9 respectively.

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.