1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * nec-enc.c - encode/decode nec firmware with key
5 * based on xorimage.c in OpenWrt
16 #define PATTERN_LEN 251
19 xor_pattern(uint8_t *data
, size_t len
, const char *key
, int k_len
, int k_off
)
26 offset
= (offset
+ 1) % k_len
;
32 static void xor_data(uint8_t *data
, size_t len
, const uint8_t *pattern
)
34 for (int i
= 0; i
< len
; i
++) {
40 static void __attribute__((noreturn
)) usage(void)
42 fprintf(stderr
, "Usage: nec-enc -i infile -o outfile -k <key>\n");
46 static unsigned char buf_pattern
[4096], buf
[4096];
48 int main(int argc
, char **argv
)
50 int k_off
= 0, ptn
= 1, c
, ret
= EXIT_SUCCESS
;
51 char *ifn
= NULL
, *ofn
= NULL
, *key
= NULL
;
55 while ((c
= getopt(argc
, argv
, "i:o:k:h")) != -1) {
72 if (optind
!= argc
|| optind
== 1) {
73 fprintf(stderr
, "illegal arg \"%s\"\n", argv
[optind
]);
79 perror("can not open input file");
83 out
= fopen(ofn
, "w");
85 perror("can not open output file");
90 fprintf(stderr
, "key is not specified\n");
94 k_len
= strnlen(key
, KEY_LEN
+ 1);
95 if (k_len
== 0 || k_len
> KEY_LEN
) {
96 fprintf(stderr
, "key length is not in range (0,%d)\n", KEY_LEN
);
100 while ((n
= fread(buf
, 1, sizeof(buf
), in
)) > 0) {
101 for (int i
= 0; i
< n
; i
++) {
102 buf_pattern
[i
] = ptn
;
105 if (ptn
> PATTERN_LEN
)
109 k_off
= xor_pattern(buf_pattern
, n
, key
, k_len
, k_off
);
110 xor_data(buf
, n
, buf_pattern
);
112 if (fwrite(buf
, 1, n
, out
) != n
) {
113 perror("failed to write");
120 perror("failed to read");