Skip to content

Commit

Permalink
Refactoring.
Browse files Browse the repository at this point in the history
* Got rid of duplicated byteswap code
  • Loading branch information
akopachov committed Oct 19, 2022
1 parent 526213c commit a55ac88
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 25 deletions.
2 changes: 1 addition & 1 deletion scenes/add_new_token/totp_scene_add_new_token.c
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ typedef struct {
InputTextSceneContext* token_secret_input_context;
InputTextSceneState* input_state;
uint32_t input_started_at;
int current_token_index;
int16_t current_token_index;
int32_t screen_y_offset;
TokenHashAlgo algo;
TokenDigitsCount digits_count;
Expand Down
27 changes: 3 additions & 24 deletions services/totp/totp.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
#include "../hmac/hmac_sha1.h"
#include "../hmac/hmac_sha256.h"
#include "../hmac/hmac_sha512.h"
#include "../hmac/byteswap.h"
#include "../timezone_utils/timezone_utils.h"

#define UINT64_GET_BYTE(integer, index) ((integer >> (8 * index)) & 0xFF)

/*
Generates the timeblock for a time in seconds.
Expand All @@ -29,22 +28,6 @@ uint64_t totp_timecode(uint8_t interval, uint64_t for_time) {
return for_time / interval;
}

/*
Converts an integer into an 8 byte array.
out_bytes is the null-terminated output string already allocated
*/
void otp_num_to_bytes(uint64_t integer, uint8_t* out_bytes) {
out_bytes[7] = UINT64_GET_BYTE(integer, 0);
out_bytes[6] = UINT64_GET_BYTE(integer, 1);
out_bytes[5] = UINT64_GET_BYTE(integer, 2);
out_bytes[4] = UINT64_GET_BYTE(integer, 3);
out_bytes[3] = UINT64_GET_BYTE(integer, 4);
out_bytes[2] = UINT64_GET_BYTE(integer, 5);
out_bytes[1] = UINT64_GET_BYTE(integer, 6);
out_bytes[0] = UINT64_GET_BYTE(integer, 7);
}

/*
Generates an OTP (One Time Password).
Expand All @@ -61,17 +44,14 @@ uint32_t otp_generate(
const uint8_t* plain_secret,
uint8_t plain_secret_length,
uint64_t input) {
uint8_t* bytes = malloc(8);
memset(bytes, 0, 8);
uint8_t* hmac = malloc(64);
memset(hmac, 0, 64);

otp_num_to_bytes(input, bytes);
uint64_t input_swapped = swap_uint64(input);

int hmac_len = (*(algo))(plain_secret, plain_secret_length, bytes, 8, hmac);
int hmac_len = (*(algo))(plain_secret, plain_secret_length, (uint8_t*)&input_swapped, 8, hmac);
if(hmac_len == 0) {
free(hmac);
free(bytes);
return OTP_ERROR;
}

Expand All @@ -82,7 +62,6 @@ uint32_t otp_generate(
i_code %= (uint64_t)pow(10, digits);

free(hmac);
free(bytes);
return i_code;
}

Expand Down

0 comments on commit a55ac88

Please sign in to comment.