Home > Back-end >  C use openssl for rsa encryption, Java use crypto rsa decryption
C use openssl for rsa encryption, Java use crypto rsa decryption

Time:09-22

This moment of time working on the problem of rsa encryption to decrypt, applauded because used c + + is playing his face ,
Nonsense not much said, the first under the environment, I am in c + + in ALT controls using the openssl library of rsa encryption, public key is to use js incoming call control method, the encryption result turn hexadecimal string is returned to the JSP page of js code, js send ajax requests to the Java background decrypted, now have some problems, as follows:
1. Public key length 1024, openssl encrypted result length of 128, but occasionally length is small, can lead to Java decrypted javax.mail. The crypto. BadPaddingException: Data must start with a zero error,
2. Such as input plaintext: test1234, decryption results: test1234 behind a pile of garbage characters as shown in the figure below


Please everyone a great god save, I have been ready to give up treatment

As key code below for everyone a great god correct, because xiaodi bucai, hope the great god correct detailed descriptions, the younger brother grateful,

C + + code is as follows:
 
/* the RSA public key encryption method */
STDMETHODIMP CsafeEdit: : RsaEncrypt (BSTR strPublicKey)
{
//g_m_string preserved the plaintext characters, this code can ignore the BEGIN
Int len=g_m_String. Length () + 2;
BSTR STR=(BSTR) ALLOC (len * 2);
If (STR==NULL)
{
Return S_FALSE;
}
if (! G_m_String. B_STR (STR, len * 2))
{
FREE (STR);
Return S_FALSE;
}
Char * mingwen=_com_util: : ConvertBSTRToString (STR);
FREE (STR);
G_m_String. The Clear ();
//g_m_string preserved the plaintext characters, this code can be ignored END

Char * p_en;//receive encrypted cryptograph
Int flen, rsa_len;

//this code is a JSP page to pass over the public key into OPENSSL BEGIN to recognize the public key
_bstr_t bstr_t (strPublicKey);
String pubKey (bstr_t);

Int nPublicKeyLen=pubKey. The size ();
For (int I=64; i {
If (pubKey [I]! )
='\ n'{
PubKey. Insert (I, "\ n");
}
i++;
}
PubKey. Insert (0, "-- -- -- -- -- BEGIN PUBLIC KEY -- -- -- -- -- \ n");
PubKey. Append (" \ n -- -- -- -- -- END PUBLIC KEY -- -- -- -- -- \ n ");
//this code is a JSP page to pass over the public key into OPENSSL identifiable public key END

//the next step is OPENSSL RSA public key encryption BEGIN
BIO BIO *=NULL;
RSA * RSA=NULL;
Char * chPublicKey=const_cast & lt; Char * & gt; (pubKey c_str ());
If ((bio=BIO_new_mem_buf (chPublicKey, 1))==NULL)//read the RSA public key from the string
{
Cout & lt; & lt; "BIO_new_mem_buf failed!" & lt; & lt; endl;
}
Rsa=PEM_read_bio_RSA_PUBKEY (bio, NULL, NULL, NULL);//from bio structure rsa structure
if (! Rsa)
{
ERR_load_crypto_strings ();
Char errBuf [512].
ERR_error_string_n (ERR_get_error (), errBuf, sizeof (errBuf));
Cout & lt; & lt; "The load public key failed [" & lt; & lt; errBuf & lt; & lt;"] "& lt; & lt; endl;
BIO_free_all (bio);
return NULL;
}
Flen=strlen (mingwen);//get clear text length, seems to be useless to
Rsa_len=RSA_size (rsa);

A moment//the following code is the place that have questions, including the allocated space to cipher p_en=(char *) malloc (rsa_len + 1); There are
//way RSA_PKCS1_PADDING rsa_len - 11 is correct, etc.

P_en=(char *) malloc (rsa_len + 1);
Memset (p_en, 0, rsa_len + 1);

If (RSA_public_encrypt (rsa_len - 11, (unsigned char *) mingwen, (unsigned char *) p_en, rsa, RSA_PKCS1_PADDING) & lt; 0 {
return NULL;
}
RSA_free (rsa);

//the following is a cipher to hexadecimal string
BIGNUM * rs.

Rs=BN_new ();
BN_bin2bn ((unsigned char *) p_en, strlen (p_en), rs);
Char * tmpData=https://bbs.csdn.net/topics/BN_bn2hex (rs);//a cipher to hexadecimal string
Int dest_len=strlen (tmpData);
For (size_t I=0; i {
G_m_String. Append (tmpData [I]);//added to the JSP page string
}

Return S_OK.
}


Java code:
 
/*
EncryptedData: is the hexadecimal ciphertext call hexStringToBytes method to get the byte array
*/
Public static byte [] decryptByPrivateKey (byte [] encryptedData, String privateKey)
Throws the Exception {



//get the private key
Byte [] keyBytes=Base64Utils. Decode (privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec=new PKCS8EncodedKeySpec (keyBytes);
KeyFactory KeyFactory=KeyFactory. GetInstance (KEY_ALGORITHM);
The Key privateK=keyFactory. GeneratePrivate (pkcs8KeySpec);

RSA Cipher Cipher=Cipher. GetInstance ("//the ECB PKCS1Padding ");
Cipher. The init (cipher DECRYPT_MODE, privateK);
Int inputLen=encryptedData. Length;
ByteArrayOutputStream out=new ByteArrayOutputStream ();
Int offSet=0;
Byte [] cache=null;
int i=0;
//to decrypt the data segment
While (inputLen - offSet & gt; 0 {
If (inputLen - offSet & gt; 128) {
Cache=cipher. DoFinal (encryptedData, offSet, 128);
} else {
Cache=cipher. DoFinal (encryptedData, offSet, inputLen - offSet);
}
Out. Write (cache, 0, cache. Length);
i++;
OffSet=I * MAX_DECRYPT_BLOCK;
}
Byte [] decryptedData=(https://bbs.csdn.net/topics/out.toByteArray);
out.close();
Return decryptedData;
}

Public static byte [] hexStringToBytes (String hexString) {
If (hexString==null | | hexString. Equals (" ")) {
return null;
}
HexString=hexString. ToUpperCase ();
Int length=hexString. Length ()/2;
Char [] hexChars=hexString. ToCharArray ();
Byte [] d=new byte (length),
for (int i=0; i Int pos=I * 2;
[I]=d (byte) (charToByte (hexChars (pos)) & lt; & lt; 4 | charToByte (hexChars/pos + 1));
}
Return d;
}
nullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnull
  • Related