00001 #include "blowfish.h"
00002
00003 namespace n2nc {
00004 namespace security {
00005
00006 BlowFish::BlowFish(key_t *key) {
00007
00008 this->loadKey(key);
00009
00010
00011
00012 EVP_EncryptInit ( &this->m_ctx_e, EVP_bf_cbc (), this->m_key, this->m_iv );
00013 EVP_DecryptInit ( &this->m_ctx_d, EVP_bf_cbc (), this->m_key, this->m_iv );
00014
00015 }
00016
00017 BlowFish::~BlowFish() {
00018 EVP_CIPHER_CTX_cleanup ( &this->m_ctx_e );
00019 EVP_CIPHER_CTX_cleanup ( &this->m_ctx_d );
00020 }
00021
00022 int BlowFish::loadKey (key_t *key) {
00023 ::memcpy ( ( void* ) this->m_key, key->key, 16 );
00024 ::bzero(key->iv,8);
00025 ::memcpy ( ( void* ) this->m_iv, key->iv, 8 );
00026
00027 ::bzero(&this->nullkey,sizeof(key_t));
00028
00029 }
00030
00031
00032 int n2nc::security::BlowFish::keyRand(key_t *key){
00033 int fd ;
00034 fd = ::open ( "/dev/random", O_RDONLY );
00035 ::read ( fd, ( void* ) key->key , 16 );
00036 return ::close ( fd );
00037 }
00038
00039 int BlowFish::reinit(){
00040
00041
00042 EVP_EncryptInit ( &this->m_ctx_e, NULL, NULL, this->m_iv );
00043 EVP_DecryptInit ( &this->m_ctx_d, NULL, NULL, this->m_iv );
00044 }
00045
00046 int BlowFish::encrypt ( void * inbuf, void * outbuf, size_t inlen ) {
00047 int olen, tlen = 0 ;
00048 int written = 0;
00049
00050 if (inlen > 65535) return -1 ;
00051
00052 if ( EVP_EncryptUpdate ( &this->m_ctx_e, (u_char*) (uint)outbuf + written, &olen, (u_char*)inbuf, inlen ) != 1 ) {
00053 std::cerr << "BlowFish: error on EVP_EncryptUpdate:" << std::endl ;
00054 return -1;
00055 }
00056
00057 if ( EVP_EncryptFinal ( &this->m_ctx_e,(u_char*)((uint)outbuf + written + olen), &tlen ) != 1 ) {
00058 std::cerr << "BlowFish: error on EVP_EncryptFinal:" << std::endl ;
00059 return -1;
00060 }
00061
00062
00063 olen += tlen;
00064 written += olen ;
00065
00066 return written;
00067 }
00068
00069 int BlowFish::decrypt ( void * inbuf, void * outbuf, size_t inlen ) {
00070 int olen, tlen = 0;
00071 int written = 0;
00072
00073 if (inlen > 65535) return -1 ;
00074
00075 if ( EVP_DecryptUpdate ( &this->m_ctx_d, (u_char*) (uint)outbuf + written, &olen, (u_char*)inbuf, inlen ) != 1 ) {
00076 std::cerr << "BlowFish: error on EVP_DecryptUpdate:" << std::endl ;
00077 return -1;
00078 }
00079
00080 if ( EVP_DecryptFinal ( &this->m_ctx_d,(u_char*)((uint)outbuf + written + olen), &tlen ) != 1 ) {
00081 std::cerr << "BlowFish: error on EVP_DecryptFinal:" << std::endl ;
00082 return -1;
00083 }
00084 olen += tlen;
00085 written += olen ;
00086
00087 return written;
00088 }
00089
00090
00091
00092
00093
00094
00095 }
00096 }
00097
00098
00099
00100