1

我正在使用下面的 JAVA 代码加密纯文本,这将创建密文,然后使用 C++ 代码中的密钥(通过 JAVA 文件中的 getSecretEncryptionKey().getEncoded() 生成)解密此密文。

JAVA代码:

    public byte[] encryptDecrypt(String jsonData, String publicKey) throws Exception
    {
        Security.addProvider(new BouncyCastleProvider());
        SecretKey secKey = getSecretEncryptionKey();

        cipherText = encryptText(jsonData, secKey);
        return cipherText;
    }

    public static SecretKey getSecretEncryptionKey() throws Exception
    {
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(256);
        SecretKey secKey = generator.generateKey();
        return secKey;
    }
    public static byte[] encryptText(String plainText, SecretKey secKey) throws Exception
    {
        // AES defaults to AES/ECB/PKCS5Padding in Java 7
        SecretKeySpec skeySpec = new SecretKeySpec(secKey.getEncoded(), "AES/ECB/PKCS7Padding");

        Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        return  aesCipher.doFinal(plainText.getBytes());
    }

C++代码:

INT32 Security::decrypt(UINT8 *ciphertext, INT32 ciphertext_len, UINT8 *key,
                UINT8 *iv, UINT8 *plaintext)
{
  EVP_CIPHER_CTX *ctx;

  INT32 len;

  INT32 plaintext_len;

  /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_ecb(), 0, key, NULL)) {
        printf("\n ERROR!! \n");
                return -1;
     }

  /* Provide the message to be decrypted, and obtain the plaintext output.
   * EVP_DecryptUpdate can be called multiple times if necessary
   */
  if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
    handleErrors();
  plaintext_len = len;

  /* Finalise the decryption. Further plaintext bytes may be written at
   * this stage.
   */
  if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
  plaintext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return plaintext_len;
}

使用 Key 解密 CipherText 时,C++ 代码生成分段错误并给出以下错误:

140159077054088:错误:06065064:数字信封例程:EVP_DecryptFinal_ex:错误解密:evp_enc.c:596:中止(核心转储)

我是这个领域的新手,所以请帮助我。

4

0 回答 0