1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-23 06:48:16 +00:00

base32: Add base32_encode & base32_encoded_length

This commit is contained in:
Saleem Rashid 2017-05-25 20:50:13 +01:00 committed by Pavol Rusnak
parent 6b7553e2f2
commit b258e7f924
2 changed files with 41 additions and 0 deletions

View File

@ -22,7 +22,28 @@
#include "base32.h" #include "base32.h"
const char *BASE32_ALPHABET_RFC4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
static inline void base32_5to8(const uint8_t *in, uint8_t length, uint8_t *out); static inline void base32_5to8(const uint8_t *in, uint8_t length, uint8_t *out);
static inline char base32_encode_character(uint8_t base32, const char *alphabet);
bool base32_encode(const uint8_t *in, size_t inlen, char *out, size_t outlen, const char *alphabet) {
size_t length = base32_encoded_length(inlen);
if (outlen <= length) {
return false;
}
base32_encode_unsafe(in, inlen, (uint8_t *) out);
for (size_t i = 0; i < length; i++) {
if (!(out[i] = base32_encode_character(out[i], alphabet))) {
return false;
}
}
out[length] = '\0';
return true;
}
void base32_encode_unsafe(const uint8_t *in, size_t inlen, uint8_t *out) { void base32_encode_unsafe(const uint8_t *in, size_t inlen, uint8_t *out) {
uint8_t remainder = inlen % 5; uint8_t remainder = inlen % 5;
@ -36,6 +57,12 @@ void base32_encode_unsafe(const uint8_t *in, size_t inlen, uint8_t *out) {
if (remainder) base32_5to8(&in[i], remainder, &out[j]); if (remainder) base32_5to8(&in[i], remainder, &out[j]);
} }
size_t base32_encoded_length(size_t inlen) {
uint8_t remainder = inlen % 5;
return (inlen / 5) * 8 + (remainder * 8 + 4) / 5;
}
void base32_5to8(const uint8_t *in, uint8_t length, uint8_t *out) { void base32_5to8(const uint8_t *in, uint8_t length, uint8_t *out) {
if (length >= 1) { if (length >= 1) {
out[0] = (in[0] >> 3); out[0] = (in[0] >> 3);
@ -64,3 +91,11 @@ void base32_5to8(const uint8_t *in, uint8_t length, uint8_t *out) {
out[7] = (in[4] & 31); out[7] = (in[4] & 31);
} }
} }
char base32_encode_character(uint8_t base32, const char *alphabet) {
if (base32 >> 5) {
return '\0';
}
return alphabet[base32];
}

View File

@ -23,9 +23,15 @@
#ifndef __BASE32_H__ #ifndef __BASE32_H__
#define __BASE32_H__ #define __BASE32_H__
#include <stdbool.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
extern const char *BASE32_ALPHABET_RFC4648;
bool base32_encode(const uint8_t *in, size_t inlen, char *out, size_t outlen, const char *alphabet);
void base32_encode_unsafe(const uint8_t *in, size_t inlen, uint8_t *out); void base32_encode_unsafe(const uint8_t *in, size_t inlen, uint8_t *out);
size_t base32_encoded_length(size_t inlen);
#endif #endif