00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #include <fstream>
00019 #include <openssl/pem.h>
00020 #include "VarRSA.h"
00021 #include "BIGNUM_xor.h"
00022 #include "CODEX_Exceptions/BignumExceptions.h"
00023 #include "CODEX_Exceptions/FileExceptions.h"
00024
00025 #include "timing.h"
00026
00027 using namespace CODEX_Ciphers;
00028 using namespace CODEX_Exceptions;
00029 using CODEX_ASN1::BigNumber;
00030 using CODEX_ASN1::SecureBigNumber;
00031
00032 VarRSAPrivateKey::VarRSAPrivateKey( const RSAPrivateKey& aKey ) :
00033 m_key( aKey )
00034 {
00035 }
00036
00037 VarRSAPrivateKey::~VarRSAPrivateKey()
00038 {
00039 }
00040
00041 BIGNUM *
00042 VarRSAPrivateKey::decrypt( const VarRSACipherText& cipherText,
00043 const HashFunction& hashFunc ) const
00044 {
00045 BIGNUM * retVal = 0;
00046 BIGNUM * c1d = 0;
00047 BIGNUM * temp = 0;
00048 BN_CTX * ctx = 0;
00049 CODEX_ASN1::ustring* tempStr = 0;
00050 unsigned char* buff = 0;
00051 try
00052 {
00053 ctx = BN_CTX_new();
00054 if ( 0 == ctx )
00055 {
00056 throw BignumContextException( __FILE__ , __LINE__ );
00057 }
00058
00059 retVal = BN_new();
00060 if ( 0 == retVal )
00061 {
00062 throw CODEX_Exceptions::BignumNullException( __FILE__ , __LINE__ );
00063 }
00064
00065
00066 c1d = exponentiate( cipherText.c1().value() );
00067
00068
00069 CODEX_ASN1::SecureBigNumber c1dbn( c1d );
00070 c1d = 0;
00071 int length = c1dbn.marshal(0);
00072 buff = new unsigned char[length];
00073 unsigned char* pBuff = buff;
00074 c1dbn.marshal(&pBuff);
00075 tempStr = hashFunc( CODEX_ASN1::ustring(buff,length),
00076 BN_num_bits(n().value()) );
00077 temp = BN_new();
00078 if ( 0 == temp )
00079 {
00080 throw BignumNullException( __FILE__ , __LINE__ );
00081 }
00082 if ( 0 == BN_bin2bn( tempStr->data(), tempStr->length(), retVal ) )
00083 {
00084 throw BignumBin2BNException( __FILE__ , __LINE__ );
00085 }
00086 if ( ! BN_mod( temp, retVal, n().value(), ctx ) )
00087 {
00088 throw BignumModException( __FILE__ , __LINE__ );
00089 }
00090 delete tempStr;
00091 tempStr = 0;
00092 delete [] buff;
00093 buff = 0;
00094
00095
00096 BIGNUM_xor( retVal, temp, cipherText.c2().value() );
00097
00098 BN_clear_free( temp );
00099 BN_CTX_free( ctx );
00100 return retVal;
00101 }
00102 catch ( ... )
00103 {
00104 if ( 0 != temp ) BN_clear_free( temp );
00105 if ( 0 != retVal ) BN_clear_free( retVal );
00106 if ( 0 != c1d ) BN_clear_free( c1d );
00107 if ( 0 != ctx ) BN_CTX_free( ctx );
00108 if ( 0 != tempStr ) delete tempStr;
00109 if ( 0 != buff ) delete [] buff;
00110 throw;
00111 }
00112 }
00113
00114 VarRSABlindPlainText*
00115 VarRSAPrivateKey::decryptBlind( const VarRSABlindCipherText& cipherText ) const
00116 {
00117 return new VarRSABlindPlainText( exponentiate( cipherText.c1().value() ),
00118 cipherText.c2() );
00119 }