使用wincrypt生成随机字符串

·

低效代码,用于生成少量随机字符串的场景。

//定义WIN32_LEAN_AND_MEAN以排除加密、DDE、RPC、Shell 和 Windows 套接字等 API。
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <wincrypt.h>
#include <stdio.h>
//两个参数,分别是接收字符串的缓冲区地址和缓冲区长度(包含结尾的0,也就是说字符串的有效长度是len-1)
BOOL GenRandomString(char *str, int len) {
  HCRYPTPROV hCryptProv;
  BYTE c;
  BOOL r = TRUE;
  if (CryptAcquireContextA(
          &hCryptProv, NULL,
          (LPCSTR) "Microsoft Base Cryptographic Provider v1.0", PROV_RSA_FULL,
          CRYPT_VERIFYCONTEXT) == FALSE) {
    return FALSE;
  }
  for (int i = 0; i < len - 1; i++) {
    if (CryptGenRandom(hCryptProv, 1, (BYTE *)&c)) {
      if (c >= 48 && c <= 57) {
        str[i] = c;
      } else if (c >= 65 && c <= 90) {
        str[i] = c;
      } else if (c >= 97 && c <= 122) {
        str[i] = c;
      } else {
        str[i] = c % 26 + 97;
      }
    } else {
      r = FALSE;
      break;
    }
  }
  CryptReleaseContext(hCryptProv, 0);
  if (r) {
    str[len - 1] = 0;
  }
  return r;
}

int main(void) {
  char str[10];
  for (int i = 0; i < 100; i++) {
    GenRandomString(str, sizeof(str));
    printf("%s\n", str);
  }
  return 1;
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注