在Windows中使用CryptoAPI Next GenerationCNG进行RSA加密/解密的错误?

如何解决在Windows中使用CryptoAPI Next GenerationCNG进行RSA加密/解密的错误?

| 我已经编写了一个代码,该代码使用以前使用CNG生成的硬编码RSA密钥对加密和解密数据。这是一个简单的程序,它仅生成一些随机输入数据,使用公钥对其进行加密,然后使用私钥对生成的加密缓冲区进行解密。我打印所有输入,中间和输出阶段,以比较解密后的明文是否与原始输入明文相同,然后重复整个加密-解密操作10次。 但是,我发现在某些情况下,加密和解密是可以的,但在其他情况下,解密的纯文本根本与输入的纯文本不匹配。这样的错误案例是完全随机和任意的,这些错误似乎没有任何模式。 这是CNG的RSA实现中的错误,还是我做错了什么? 代码如下:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <bcrypt.h>

#define NT_SUCCESS(Status)          (((NTSTATUS)(Status)) >= 0)
#define STATUS_UNSUCCESSFUL         ((NTSTATUS)0xC0000001L)

#define PrivateKeySize 283
#define PublicKeySize 155
#define InputDataSize 128

PUCHAR encryptedBuffer;
ULONG encryptedBufferSize = 128;


VOID printMem(PVOID Mem,int length)
{
    int i;
    for (i = 0; i < length; i++)
        printf(\"%02x \",((unsigned char *)Mem)[i]);
}

VOID Decrypt()
{
    unsigned char PrivateKey[PrivateKeySize] = {0x52,0x53,0x41,0x32,0x00,0x04,0x03,0x80,0x40,0x01,0xB7,0x50,0x52,0xDD,0x58,0xE4,0x96,0xAF,0x91,0xE5,0xB2,0x7B,0x0A,0xE6,0xAA,0x1F,0x71,0x8A,0x66,0xC3,0xF0,0x21,0xD8,0x2C,0xD6,0x25,0x2E,0x77,0x3C,0x61,0x08,0x1B,0x69,0xE7,0xDF,0x3B,0x07,0xFE,0xF1,0xDB,0xBF,0xA6,0x35,0xC7,0x49,0x06,0xC8,0x74,0x2A,0xB9,0xED,0xB3,0x75,0x5F,0xD0,0x14,0x0E,0x81,0x18,0x5E,0x34,0x5A,0xC2,0x3A,0x84,0x63,0xB1,0x6B,0x7F,0xE0,0xF3,0x43,0x8F,0x7C,0xF2,0x29,0x28,0x20,0x36,0xC0,0x92,0x17,0x42,0x99,0x72,0x82,0xBE,0x8E,0x3F,0xC9,0xE1,0xC4,0x68,0x73,0x1D,0x67,0x8D,0xA3,0xB4,0xBA,0xB0,0x9B,0xBB,0xB8,0x6E,0x1E,0xA0,0x4B,0x6D,0x47,0xA5,0x39,0x05,0x27,0xD4,0xD1,0x38,0x5B,0x16,0x64,0xD5,0x19,0xDA,0xBD,0xAB,0x54,0x98,0x90,0x83,0x6A,0x1C,0x2D,0xFA,0x9E,0x26,0xB5,0xF8,0x4A,0x9C,0x89,0x12,0xFF,0x60,0x87,0xC1,0xC5,0xAE,0x11,0x37,0xE3,0x9D,0xBC,0x85,0xD2,0xEF,0xCD,0x93,0x33,0xFC,0xE7};
    BCRYPT_ALG_HANDLE hAlgorithm = NULL;
    BCRYPT_KEY_HANDLE hKey = NULL;
    ULONG plaintextSize = 128;
    PUCHAR decryptedBuffer;
    ULONG decryptedBufferSize;
    NTSTATUS status;

    status = BCryptOpenAlgorithmProvider(&hAlgorithm,BCRYPT_RSA_ALGORITHM,NULL,0);
    if (!NT_SUCCESS(status)) {
        printf(\"Failed to get algorithm provider..status : %08x\\n\",status);
        goto cleanup;
    }

    status = BCryptImportKeyPair( hAlgorithm,BCRYPT_RSAPRIVATE_BLOB,&hKey,PrivateKey,PrivateKeySize,BCRYPT_NO_KEY_VALIDATION);
    if (!NT_SUCCESS(status)) {
        printf(\"Failed to import Private key..status : %08x\\n\",status);
        goto cleanup;
    }

    status = BCryptDecrypt( hKey,encryptedBuffer,encryptedBufferSize,&decryptedBufferSize,0);
    if (!NT_SUCCESS(status)) {
        printf(\"Failed to get required size of buffer..status : %08x\\n\",status);
        goto cleanup;
    }

    decryptedBuffer = (PUCHAR)HeapAlloc (GetProcessHeap (),decryptedBufferSize);
    if (decryptedBuffer == NULL) {
        printf(\"failed to allocate memory for buffer\\n\");
        goto cleanup;
    }

    status = BCryptDecrypt( hKey,decryptedBuffer,decryptedBufferSize,0);
    if (!NT_SUCCESS(status)) {
        printf(\"Failed decrypt buffer..status : %08x\\n\",status);
        goto cleanup;
    }

    printf(\"Decrypted buffer\\n\");
    printMem(decryptedBuffer,decryptedBufferSize);
    printf(\"\\n\\n\");

cleanup:
    HeapFree(GetProcessHeap(),decryptedBuffer);

    BCryptDestroyKey(hKey);

    BCryptCloseAlgorithmProvider(hAlgorithm,0);
}


VOID Encrypt()
{
    unsigned char PublicKey[PublicKeySize] = {0x52,0x31,0x9B};
    unsigned char InputData[InputDataSize];
    BCRYPT_ALG_HANDLE hAlgorithm = NULL;
    BCRYPT_KEY_HANDLE hKey = NULL;
    NTSTATUS status;

    for (int i=0; i<128; i++)
        InputData[i] = (unsigned char)rand();

    printf(\"Random Data is \\n\");
    printMem(InputData,InputDataSize);
    printf(\"\\n\\n\");

    status = BCryptOpenAlgorithmProvider(    &hAlgorithm,0 );
    if (!NT_SUCCESS(status)) {
        printf(\"Failed to get algorithm provider..status : %08x\\n\",BCRYPT_RSAPUBLIC_BLOB,PublicKey,155,BCRYPT_NO_KEY_VALIDATION );
    if (!NT_SUCCESS(status)) {
        printf(\"Failed to import Private key..status : %08x\\n\",status);
        goto cleanup;

    }

    status = BCryptEncrypt( hKey,InputData,InputDataSize,&encryptedBufferSize,0
                            );
    if (!NT_SUCCESS(status)) {
        printf(\"Failed to get required size of buffer..status : %08x\\n\",status);
        goto cleanup;
    }

    encryptedBuffer = (PUCHAR)HeapAlloc (GetProcessHeap (),encryptedBufferSize);

    if (encryptedBuffer == NULL) {
        printf(\"failed to allocate memory for blindedFEKBuffer\\n\");
        goto cleanup;
    }

    status = BCryptEncrypt( hKey,0
                            );

    if (!NT_SUCCESS(status))    {
        printf(\"Failed encrypt data..status : %08x\\n\",status);
        goto cleanup;
    }

printf(\"Encrypted Data\\n\");
printMem(encryptedBuffer,encryptedBufferSize);
printf(\"\\n\\n\");

cleanup:
            if(hKey)
                BCryptDestroyKey(hKey);
            if(hAlgorithm)
                BCryptCloseAlgorithmProvider(hAlgorithm,0);
}


int __cdecl wmain(
                   int argc,__in_ecount(argc) LPWSTR *wargv)
{

    int i;
    for (i=0; i<10; i++)
    {
        Encrypt();
        Decrypt();
    }

}
    

解决方法

        这不是CNG中的错误,而是原始RSA加密工作方式的产物。您正在加密的某些随机值大于密钥的模数(该模数是RSA密钥中2个素数的值相乘),这意味着值会回绕(如果设置为“ 1”,您会看到输入和输出始终匹配)。 您还希望将
BCRYPT_PAD_PKCS1
BCRYPT_PAD_OAEP
传递给
BCryptEncrypt
/
BCryptDecrypt
的dwFlags参数,因为原始RSA加密不安全。如果您使用
BCRYPT_PAD_OAEP
,则还必须提供
BCRYPT_OAEP_PADDING_INFO structure
。     ,        您的问题是否可能是由于将
NULL
IV传递给
BCryptEncrypt
而导致的,如下面社区注释中所述: BCryptEncrypt函数     ,        我尝试了您的代码,如果我使
InputData
的生成是静态的而不是随机的,例如:
ZeroMemory( InputData,InputDataSize );
std::string strInput = \"This is just a test with a long long... very long string\";
for( int i = 0; i < (int)strInput.size(); i++ )
{
    InputData[i] = strInput[i];
}
它不返回任何错误,我认为rand()的极值存在问题。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-