Files

49 lines
2.1 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* rsa_raw_test.c — 验证 weapi 需要的 textbook RSA(无 padding 模幂)
* 用 mbedtls_rsa_public() 对固定 16 字节消息做 c = m^e mod n,
* 输出定长 256 hex(与模数等长)。宿主用 Python pow(m,e,n) 交叉校验。
* 编译(mipsel): .tools/zig-mipsel-cc -O2 -static -Ivendor/mbedtls/include rsa_raw_test.c \
* out/mbedtls/mipsel/libmbedcrypto.a -o out/rsa_raw_test
*/
#include <stdio.h>
#include <string.h>
#include "mbedtls/rsa.h"
#include "mbedtls/pk.h"
#include "mbedtls/base64.h"
/* PUBLIC_KEY_DER_B64 (PKCS#8 / SubjectPublicKeyInfo, 1024-bit RSA) */
static const char *PEM_DER_B64 =
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgtQn2JZ34ZC28NWYpAUd98iZ37BUrX/aKzmFbt7clFSs6sXqHauqKWqdtLkF2KexO40H1YTX8z2lSgBBOAxLsvaklV8k4cBFK9snQXE9/DDaFt6Rr7iVZMldczhC0JNgTz+SHXT6CBHuX3e9SdB1Ua44oncaTWz7OBGLbCiK45wIDAQAB";
int main(void) {
unsigned char der[512], *buf = der; size_t der_len = sizeof der;
/* 解码 base64 DER */
if (mbedtls_base64_decode(der, sizeof der, &der_len, (const unsigned char*)PEM_DER_B64, strlen(PEM_DER_B64)) != 0) {
printf("base64 decode fail\n"); return 1;
}
/* 解析公钥 */
mbedtls_pk_context pk; mbedtls_pk_init(&pk);
if (mbedtls_pk_parse_public_key(&pk, der, der_len) != 0) {
printf("pk parse fail\n"); return 1;
}
mbedtls_rsa_context *rsa = mbedtls_pk_rsa(pk);
int keylen = mbedtls_rsa_get_len(rsa);
printf("rsa len=%d (bytes)\n", keylen);
/* 固定 16 字节明文(weapi 的 secret_key),右对齐到 keylen 后做 raw 模幂 */
unsigned char secret[16];
for (int i = 0; i < 16; i++) secret[i] = (unsigned char)(0x41 + i); /* 测试向量 */
unsigned char input[256], output[256];
memset(input, 0, sizeof input);
memcpy(input + keylen - 16, secret, 16);
int rc = mbedtls_rsa_public(rsa, input, output); /* 无 padding 纯模幂 */
if (rc != 0) { printf("rsa_public fail %d\n", rc); return 1; }
printf("secret = ");
for (int i = 0; i < 16; i++) printf("%02X", secret[i]);
printf("\nCT = ");
for (int i = 0; i < keylen; i++) printf("%02X", output[i]);
printf("\n");
mbedtls_pk_free(&pk);
return 0;
}