made Log::prng() a class method so it can be used for decryption
[opencorn.git] / log / log.rb
blobe2a93c90703e6c6a1d1b4064cd487cd543010226
1 require 'openssl'
2 require 'base64'
3 require 'opencorn/config'
4 require 'gpgme'
5 require 'singleton'
8 module OpenCorn
9   class Log
10     include Singleton
11     @seed = nil
13     def initialize
14       @seed=nil
15       @seed = OpenSSL::Random::random_bytes(128)
16       gpgdata = GPGME::Data.from_str(@seed)
17       gpgkeys = GPGME.list_keys(OpenCorn::Config['GPG_LOG_KEYID'])
18       raise "Too many keys for this KeyID" unless gpgkeys.size == 1
19       gpgout = GPGME.encrypt(gpgkeys,gpgdata)
20       #preceding 00 01 indicates a new seed for the prng encrypted with
21       writeLog("\x00\x01"+Base64::encode64(gpgout))
22       puts "OpenCorn::Log initialized"
23     end
25     def prng(seed)
26       ctx = Digest::SHA512
27       [ctx.digest("0"+seed),ctx.digest("1"+seed)]
28     end
30     def writeLog(msg)
31       fp = File.open(OpenCorn::Config['LOG_FILE'],"a")
32       fp.write(msg)
33       fp.close
34     end
36     def getRand()
37         @seed,out = prng(@seed)
38         out
39     end
41     def cryptMsg(msg)
42         myrand = getRand()
43         ctx = OpenSSL::Cipher::AES256.new("OFB")
44         ctx.iv  = myrand[0..15]  #128bit iv
45         ctx.key = myrand[16..47] #256bit key
46         ctext = ctx.update(msg)+ctx.final()
47         out = OpenSSL::HMAC.digest("SHA1",myrand[48..63],ctext)+ctext 
48         #preceding 00 indicates that the base64 string is as symmetric
49         #encrypted logentry
50         writeLog("\x00"+Base64::encode64(out))
51     end
52     alias << cryptMsg
53   end
54 end