ARM Shanghai IoT Team (Internal) / newMiniTLS-GPL

Fork of MiniTLS-GPL by Donatien Garnier

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers crypto_arc4.c Source File

crypto_arc4.c

Go to the documentation of this file.
00001 /*
00002 MiniTLS - A super trimmed down TLS/SSL Library for embedded devices
00003 Author: Donatien Garnier
00004 Copyright (C) 2013-2014 AppNearMe Ltd
00005 
00006 This program is free software; you can redistribute it and/or
00007 modify it under the terms of the GNU General Public License
00008 as published by the Free Software Foundation; either version 2
00009 of the License, or (at your option) any later version.
00010 
00011 This program is distributed in the hope that it will be useful,
00012 but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014 GNU General Public License for more details.
00015 
00016 You should have received a copy of the GNU General Public License
00017 along with this program; if not, write to the Free Software
00018 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
00019 *//**
00020  * \file crypto_arc4.c
00021  * \copyright Copyright (c) AppNearMe Ltd 2014
00022  * \author Donatien Garnier
00023  */
00024 
00025 #include "core/fwk.h"
00026 #include "crypto_arc4.h"
00027 #include "crypto_macros.h"
00028 
00029 void crypto_arc4_init(crypto_arc4_t* arc4, const uint8_t* key, size_t key_size)
00030 {
00031   int i;
00032   int j;
00033   uint8_t b;
00034 
00035   arc4->i = 0;
00036   arc4->j = 0;
00037 
00038   for(i = 0; i < 256; i++)
00039   {
00040     arc4->state[i] = i;
00041   }
00042 
00043   for( i = j = 0; i < 256; i++)
00044   {
00045     //Shuffle using key
00046     j = (j + arc4->state[i] + key[i % key_size]) & 0xFF;
00047 
00048     //Swap
00049     b = arc4->state[i];
00050     arc4->state[i] = arc4->state[j];
00051     arc4->state[j] = b;
00052   }
00053 }
00054 
00055 void crypto_arc4_encrypt(crypto_arc4_t* arc4, const uint8_t* plaintext, uint8_t* ciphertext, size_t length)
00056 {
00057   uint8_t b;
00058 
00059   while(length--)
00060   {
00061     arc4->i = (arc4->i + 1) & 0xFF;
00062     arc4->j = (arc4->j + arc4->state[arc4->i]) & 0xFF;
00063 
00064     //Swap
00065     b = arc4->state[arc4->i];
00066     arc4->state[arc4->i] = arc4->state[arc4->j];
00067     arc4->state[arc4->j] = b;
00068 
00069     *ciphertext = *plaintext ^ arc4->state[ (arc4->state[arc4->i] + arc4->state[arc4->j]) & 0xFF ];
00070     ciphertext++;
00071     plaintext++;
00072   }
00073 }
00074 
00075 void crypto_arc4_process(crypto_arc4_t* arc4, buffer_t* buffer)
00076 {
00077   uint8_t* text = buffer_current_read_position(buffer);
00078   size_t size = buffer_length(buffer);
00079 
00080   crypto_arc4_encrypt(arc4, text, text, size);
00081 }