1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * xorimage.c - partially based on OpenWrt's addpattern.c
15 static char default_pattern
[] = "12345678";
16 static int is_hex_pattern
;
19 int xor_data(void *data
, size_t len
, const void *pattern
, int p_len
, int p_off
)
21 const uint8_t *key
= pattern
;
27 p_off
= (p_off
+ 1) % p_len
;
33 void usage(void) __attribute__ (( __noreturn__
));
37 fprintf(stderr
, "Usage: xorimage [-i infile] [-o outfile] [-p <pattern>] [-x]\n");
42 int main(int argc
, char **argv
)
44 char buf
[1024]; /* keep this at 1k or adjust garbage calc below */
49 const char *pattern
= default_pattern
;
50 char hex_pattern
[128];
56 while ((c
= getopt(argc
, argv
, "i:o:p:xh")) != -1) {
68 is_hex_pattern
= true;
76 if (optind
!= argc
|| optind
== 1) {
77 fprintf(stderr
, "illegal arg \"%s\"\n", argv
[optind
]);
81 if (ifn
&& !(in
= fopen(ifn
, "r"))) {
82 fprintf(stderr
, "can not open \"%s\" for reading\n", ifn
);
86 if (ofn
&& !(out
= fopen(ofn
, "w"))) {
87 fprintf(stderr
, "can not open \"%s\" for writing\n", ofn
);
91 p_len
= strlen(pattern
);
94 fprintf(stderr
, "pattern cannot be empty\n");
101 if ((p_len
/ 2) > sizeof(hex_pattern
)) {
102 fprintf(stderr
, "provided hex pattern is too long\n");
106 if (p_len
% 2 != 0) {
107 fprintf(stderr
, "the number of characters (hex) is incorrect\n");
111 for (i
= 0; i
< (p_len
/ 2); i
++) {
112 if (sscanf(pattern
+ (i
* 2), "%2x", &hex_buf
) < 0) {
113 fprintf(stderr
, "invalid hex digit around %d\n", i
* 2);
116 hex_pattern
[i
] = (char)hex_buf
;
120 while ((n
= fread(buf
, 1, sizeof(buf
), in
)) > 0) {
121 if (n
< sizeof(buf
)) {
124 fprintf(stderr
, "fread error\n");
129 if (is_hex_pattern
) {
130 p_off
= xor_data(buf
, n
, hex_pattern
, (p_len
/ 2),
133 p_off
= xor_data(buf
, n
, pattern
, p_len
, p_off
);
136 if (!fwrite(buf
, n
, 1, out
)) {
138 fprintf(stderr
, "fwrite error\n");