gnuk/src/random.c

73 lines
1.7 KiB
C
Raw Normal View History

2010-09-04 09:44:01 +00:00
/*
2010-09-05 16:55:29 +00:00
* random.c -- get random bytes
*
* Copyright (C) 2010 Free Software Initiative of Japan
* Author: NIIBE Yutaka <gniibe@fsij.org>
*
* This file is a part of Gnuk, a GnuPG USB Token implementation.
*
* Gnuk is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Gnuk is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
2010-09-04 09:44:01 +00:00
*/
2010-09-05 16:55:29 +00:00
#include "config.h"
#include "ch.h"
#include "gnuk.h"
2010-09-04 09:44:01 +00:00
2010-09-05 16:55:29 +00:00
extern void *_binary_random_bits_start;
2010-09-04 09:44:01 +00:00
2010-09-05 16:55:29 +00:00
const uint8_t *
random_bytes_get (void)
2010-09-04 09:44:01 +00:00
{
2010-09-09 16:25:44 +00:00
uint32_t addr, addr0;
2010-09-04 09:44:01 +00:00
2010-09-05 16:55:29 +00:00
addr = (uint32_t)&_binary_random_bits_start + ((hardclock () << 5) & 0x3e0);
2010-09-09 16:25:44 +00:00
addr0 = addr;
while (1)
{
if (*(uint32_t *)addr != 0)
break;
addr += 32;
if (addr >= ((uint32_t)&_binary_random_bits_start) + 1024)
addr = ((uint32_t)&_binary_random_bits_start);
if (addr == addr0)
fatal ();
}
2010-09-04 09:44:01 +00:00
2010-09-05 16:55:29 +00:00
return (const uint8_t *)addr;
2010-09-04 09:44:01 +00:00
}
2010-09-05 16:55:29 +00:00
void
random_bytes_free (const uint8_t *p)
2010-09-04 09:44:01 +00:00
{
2010-09-09 16:25:44 +00:00
int i;
uint32_t addr = (uint32_t)p;
for (i = 0; i < 16; i++)
flash_clear_halfword (addr+i*2);
2010-09-04 09:44:01 +00:00
}
2010-09-05 16:55:29 +00:00
uint32_t
get_random (void)
2010-09-04 09:44:01 +00:00
{
2010-09-05 16:55:29 +00:00
const uint32_t *p = (const uint32_t *)random_bytes_get ();
2010-09-09 16:25:44 +00:00
uint32_t r = *p;
random_bytes_free ((const uint8_t *)p);
return r;
2010-09-04 09:44:01 +00:00
}