[U-Boot] [PATCH v3 45/54] Add rivest cipher 4 (rc4) implementation

Simon Glass sjg at chromium.org
Tue Jun 23 23:39:07 CEST 2015


Add an implementation of RC4. This will be used by Rockchip booting but may
be useful in other situations.

Signed-off-by: Simon Glass <sjg at chromium.org>
---

Changes in v3: None
Changes in v2: None

 include/rc4.h | 21 +++++++++++++++++++++
 lib/Makefile  |  1 +
 lib/rc4.c     | 49 +++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 71 insertions(+)
 create mode 100644 include/rc4.h
 create mode 100644 lib/rc4.c

diff --git a/include/rc4.h b/include/rc4.h
new file mode 100644
index 0000000..ea409c2
--- /dev/null
+++ b/include/rc4.h
@@ -0,0 +1,21 @@
+/*
+ * (C) Copyright 2015 Google, Inc
+ *
+ * (C) Copyright 2008-2014 Rockchip Electronics
+ *
+ * SPDX-License-Identifier:	GPL-2.0+
+ */
+
+#ifndef __RC4_H
+#define __RC4_H
+
+/**
+ * rc4_encode() - encode a buf with the RC4 cipher
+ *
+ * @buf:	Buffer to encode (it is overwrite in the process
+ * @len:	Length of buffer in bytes
+ * @key:	16-byte key to use
+ */
+void rc4_encode(unsigned char *buf, unsigned int len, unsigned char key[16]);
+
+#endif
diff --git a/lib/Makefile b/lib/Makefile
index 1139f9b..fd106b9 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -37,6 +37,7 @@ obj-$(CONFIG_MD5) += md5.o
 obj-y += net_utils.o
 obj-$(CONFIG_PHYSMEM) += physmem.o
 obj-y += qsort.o
+obj-y += rc4.o
 obj-$(CONFIG_SHA1) += sha1.o
 obj-$(CONFIG_SUPPORT_EMMC_RPMB) += sha256.o
 obj-$(CONFIG_SHA256) += sha256.o
diff --git a/lib/rc4.c b/lib/rc4.c
new file mode 100644
index 0000000..89d15f3
--- /dev/null
+++ b/lib/rc4.c
@@ -0,0 +1,49 @@
+/*
+ * (C) Copyright 2015 Google, Inc
+ *
+ * (C) Copyright 2008-2014 Rockchip Electronics
+ *
+ * Rivest Cipher 4 (RC4) implementation
+ *
+ * SPDX-License-Identifier:	GPL-2.0+
+ */
+
+#ifndef USE_HOSTCC
+#include <common.h>
+#endif
+#include <rc4.h>
+
+void rc4_encode(unsigned char *buf, unsigned int len, unsigned char key[16])
+{
+	unsigned char s[256], k[256], temp;
+	unsigned short i, j, t;
+	int ptr;
+
+	j = 0;
+	for (i = 0; i < 256; i++) {
+		s[i] = (unsigned char)i;
+		j &= 0x0f;
+		k[i] = key[j];
+		j++;
+	}
+
+	j = 0;
+	for (i = 0; i < 256; i++) {
+		j = (j + s[i] + k[i]) % 256;
+		temp = s[i];
+		s[i] = s[j];
+		s[j] = temp;
+	}
+
+	i = 0;
+	j = 0;
+	for (ptr = 0; ptr < len; ptr++) {
+		i = (i + 1) % 256;
+		j = (j + s[i]) % 256;
+		temp = s[i];
+		s[i] = s[j];
+		s[j] = temp;
+		t = (s[i] + (s[j] % 256)) % 256;
+		buf[ptr] = buf[ptr] ^ s[t];
+	}
+}
-- 
2.4.3.573.g4eafbef



More information about the U-Boot mailing list