Crypto/b64_random url-safe maken

svn path=/Slnkdwf/trunk/; revision=30297
This commit is contained in:
Jos Groot Lipman
2016-08-15 12:09:15 +00:00
parent be003ff41f
commit ae6c972528

View File

@@ -16,11 +16,17 @@ static const char *base64_chars =
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
// https://tools.ietf.org/html/rfc4648#page-7
static const char *base64_chars_urlsafe =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789-_";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
CString base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len, BOOL padding) {
CString base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len, BOOL padding, const char *charset = base64_chars) {
CString ret;
int i = 0;
int j = 0;
@@ -36,7 +42,7 @@ CString base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len,
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
ret += charset[char_array_4[i]];
i = 0;
}
}
@@ -52,7 +58,7 @@ CString base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len,
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
ret += charset[char_array_4[j]];
while(padding && (i++ < 3))
ret += '=';
@@ -158,7 +164,7 @@ STDMETHODIMP CCrypto::hex_pbkdf2(BSTR pPassword, BSTR pSalt, ULONG pCount, ULONG
/* T_1 = U_1 ... */
memcpy(T, U, SHA1_MAC_LEN);
for (uint64_t j = 2; j <= pCount; j++)
for (uint64_t j = 2; j <= pCount; j++)
{
/* Compute U_j. */
HMAC_SHA1.HMAC_SHA1(U, SHA1_MAC_LEN, passbuff, passlen, U);
@@ -264,6 +270,7 @@ BOOLEAN NTAPI RtlGenRandom(PVOID RandomBuffer, ULONG RandomBufferLength);
# pragma comment(lib, "advapi32.lib")
// pLength is het aantal bytes. De resulterende b64 zal langer zijn
// Merk op: we leveren een url en filename safe string op
STDMETHODIMP CCrypto::b64_random(ULONG pLength, BSTR* pVal)
{
if (pLength > 32)
@@ -274,7 +281,7 @@ STDMETHODIMP CCrypto::b64_random(ULONG pLength, BSTR* pVal)
if (!RtlGenRandom(bytes, pLength))
return myAtlReportError(GetObjectCLSID(), "ERROR CCrypto::b64_random: RtlGenRandom failed");
CString res = base64_encode(bytes, pLength, false); // no padding
CString res = base64_encode(bytes, pLength, false, base64_chars_urlsafe); // no padding
SecureZeroMemory(bytes, pLength);
CComBSTR bstrString(res);