common.c revision 323134
1/* 	$OpenBSD: common.c,v 1.2 2015/01/08 13:10:58 djm Exp $ */
2/*
3 * Helpers for key API tests
4 *
5 * Placed in the public domain
6 */
7
8#include "includes.h"
9
10#include <sys/types.h>
11#include <sys/param.h>
12#include <sys/stat.h>
13#include <fcntl.h>
14#include <stdio.h>
15#ifdef HAVE_STDINT_H
16#include <stdint.h>
17#endif
18#include <stdlib.h>
19#include <string.h>
20#include <unistd.h>
21
22#include <openssl/bn.h>
23#include <openssl/rsa.h>
24#include <openssl/dsa.h>
25#include <openssl/objects.h>
26#ifdef OPENSSL_HAS_NISTP256
27# include <openssl/ec.h>
28#endif
29
30#include "../test_helper/test_helper.h"
31
32#include "ssherr.h"
33#include "authfile.h"
34#include "sshkey.h"
35#include "sshbuf.h"
36
37#include "common.h"
38
39struct sshbuf *
40load_file(const char *name)
41{
42	int fd;
43	struct sshbuf *ret;
44
45	ASSERT_PTR_NE(ret = sshbuf_new(), NULL);
46	ASSERT_INT_NE(fd = open(test_data_file(name), O_RDONLY), -1);
47	ASSERT_INT_EQ(sshkey_load_file(fd, ret), 0);
48	close(fd);
49	return ret;
50}
51
52struct sshbuf *
53load_text_file(const char *name)
54{
55	struct sshbuf *ret = load_file(name);
56	const u_char *p;
57
58	/* Trim whitespace at EOL */
59	for (p = sshbuf_ptr(ret); sshbuf_len(ret) > 0;) {
60		if (p[sshbuf_len(ret) - 1] == '\r' ||
61		    p[sshbuf_len(ret) - 1] == '\t' ||
62		    p[sshbuf_len(ret) - 1] == ' ' ||
63		    p[sshbuf_len(ret) - 1] == '\n')
64			ASSERT_INT_EQ(sshbuf_consume_end(ret, 1), 0);
65		else
66			break;
67	}
68	/* \0 terminate */
69	ASSERT_INT_EQ(sshbuf_put_u8(ret, 0), 0);
70	return ret;
71}
72
73BIGNUM *
74load_bignum(const char *name)
75{
76	BIGNUM *ret = NULL;
77	struct sshbuf *buf;
78
79	buf = load_text_file(name);
80	ASSERT_INT_NE(BN_hex2bn(&ret, (const char *)sshbuf_ptr(buf)), 0);
81	sshbuf_free(buf);
82	return ret;
83}
84
85