nunojob:~ dscape/08$ echo The Black Sheep

Archive for the ‘Projects’ Category

RSA Encrypt & Decrypt in ruby

Well I finished the encrypt with RSA on ruby some hours ago and felt like sharing :)

Case you feel like doing something back for me just download the latest release of my beta twitter client and send me some comments to my email. It’s pretty hard to test something when my environment is completely contaminated !

require 'openssl'
require 'Base64'

class Rudolph
  class Crypt
    def initialize data_path
      @data_path = data_path
      @private   = get_key 'id_rsa'
      @public    = get_key 'id_rsa.pub'
    end

    def encrypt_string message
      Base64::encode64(@public.public_encrypt(message)).rstrip
    end

    def decrypt_string message
      @private.private_decrypt Base64::decode64(message)
    end

    def self.generate_keys data_path
      rsa_path = File.join(data_path, 'rsa')
      privkey  = File.join(rsa_path, 'id_rsa')
      pubkey   = File.join(rsa_path, 'id_rsa.pub')
      unless File.exists?(privkey) || File.exists?(pubkey)
        keypair  = OpenSSL::PKey::RSA.generate(1024)
        Dir.mkdir(rsa_path) unless File.exist?(rsa_path)
        File.open(privkey, 'w') { |f| f.write keypair.to_pem } unless File.exists? privkey
        File.open(pubkey, 'w') { |f| f.write keypair.public_key.to_pem } unless File.exists? pubkey
      end
    end

    private
    def get_key filename
      OpenSSL::PKey::RSA.new File.read(File.join(@data_path, 'rsa', filename))
    end
  end
end

Open Source Online Testing System (OSOTS)

I simply can’t believe that I forgot to post this project in my blog. Anyway if you have to deploy a multiple choice test and you feel like messing arround with Ruby on Rails and DB2 here goes the link.

Open Source Online Testing System (OSOTS)

Yet Another Ruby on Rails Web Application – Teaser

Integração entre RSpec & TextMate

Como já disse anteriormente ando a trabalhar no CouchDB-Ruby driver. Como a coisa tem o seu nível de exigência decidi usar rspec, algo que já andava para fazer a algum tempo, de forma a melhorar a testagem do software que produzo e reduzir o tempo de implementação. Já agora aproveito para sugerir o ZenTest a quem quiser que o rspec corra em background.

Continuando: rspec é uma forma descritiva – tipo cenários em Use Case – para descrever os nossos testes. Em Ruby claro, dai o R :P

O resultado final fica assim. É catita e prático, já que evita mais uma ida a consola para escrever ‘spec filename.rb’! E é bastante parecida com a linguagem natural. Por exemplo – um dos meus primeiros testes é:

it "should connect to server and return a Server object" do
  CouchDB.connect(HOST, PORT).should 
    be_kind_of(CouchDB::Server)
end

Não fiz commit de nada porque a implementaçao anterior do CouchDB-Ruby com JSON não está completa. Portanto não vale a pena ir espreitar que não está nada lá! Em breve, espero eu, podem ver os testes completos online.

De qualquer forma se estiverem interessados em experimentar o rspec basta:

  • Instalar o rspec
    sudo gem install rspec
  • Descobrir o path onde está o ruby e o rspec. Estes comandos são capazes de ajudar:
    which ruby
    gem environment
  • Com os meus paths basta correr:
    export TM_RUBY=/usr/bin/ruby
    export TM_RSPEC_HOME=/Library/Ruby/Gems/1.8/gems/rspec-1.1.3
    cd ~/Library/Application\ Support/TextMate/Bundles/
    svn co svn://rubyforge.org/var/svn/rspec/trunk/RSpec.tmbundle
    
  • Como o (meu) terminal não gosta de exports. Caso não funcione façam:
    echo TM_RUBY=/usr/bin/ruby >> ~/.profile
    echo TM_RSPEC_HOME=/Library/Ruby/Gems/1.8/gems/rspec-1.1.3 >> ~/.profile
    
  • Actualizar os Bundles do TextMate
    Bundles > Bundle Editor > Reload Bundles

E pronto! Caso surjam dúvidas podem sempre consultar a documentação oficial do bundle rspec para TextMate. Que comece a diversão! Bem vá diversão é exagerar mas com rspec é pelo menos uma experiência mais agradável que o habitual quando se fala de testes.

Random in Ruby on Rails

So your doing a find on your model and you want a random instance. I didn’t find a method to do this so I decided to make my own.

In this case I wanted a random quote. So after generating the model all I had to do was:

def self.random
  Quote.find_by_id rand(Quote.count) + 1
end

And now you can simply call your random quotes in any controller action you desire. Just

@rquote = Quote.random

If this is the lamest ruby ever please feel free to give me some feedback :) I will be delighted to learn a different way!

[EDIT: Discussion about this at Rails Core]

This version of RMagick was created to run with ImageMagick 6.3.3 but ImageMagick 6.3.8 is in use

A paciencia tem os seus limites e vou dormir. Se entretanto alguém descobrir a solução para isto peço-lhe o favor de me deixar nos comentários.

xForms Example (CSS)

Sample Xforms Application using cssSo here comes my first ever XForms sample. If you are interested in testing them out I’ll have to give you some pointers. First off all your browser probably can’t render XForms. So you need to find a specific add-on for your browser to make it work. As this XForms where made in Mozilla Firefox with this add-on I strongly recommend that you use it to get the same results. This is not my fault, XForms is not as mature as HTML or CSS and therefor these things tend to happen. You will see what I’m talking about when I get to the Know Issues! :PNow two short notes:

  • For the load/save button to work you will need to change the path in the code. Just look for xforms:submission and replace the filepath for the one in your computer.
  • You need to comment what’s between this for the load button to work. Why? The bind is interfering with the instance replace. How do you fix it? If i knew I would have. I think that when I do remove the bind and add the schema this behavior will be fixed..

<!– remove this lines to erase load bug. Using a schema will fix this –><!– EOB: End of bug –>

Credits for the icons go to famfamfam.Here is the list of known issues (any help is welcome):

  • Not binded to the schema. That’s because I’m lasy and METS is hard work.
  • xforms:select1 won’t hide the scroll on overflow:hidden. I’m not sure this is my responsibility as the add-on doesn’t represent a full XForms implementation.
  • Submission not implemented. That was really not the point.
  • Submission button is relevant when no authorid or workid is given. Anyone?
  • Can’t style ‘add’ and ‘remove’ trigger differently from the other xforms|trigger. I tried creating a class for them having as result a weird inverted triagle. To replicate this bug you need to find a trigger and add style=”border:100px;”.

For now: that’s all folks! Have a nice week.

Pluggable Authentication Modules

Este trabalho serve como introdução aos Plugglable Authentication Modules (PAM), do ponto de vista da administração de sistemas e desenvolvimento de aplicações num ambiente Linux. São também abordadas as temáticas da segurança e do desenvolvimento de novos módulos. Para finalizar é apresentado um pequeno exemplo prático em como desenvolver uma aplicação PAM-aware. 

Quem estiver interessado numa breve introdução ao PAM basta carregar aqui.

Uma pequena introdução as assinaturas digitais XML

De acordo com o RFC2828 uma assinatura digital define-se como sendo um valor calculado com um algoritmo criptográfico e anexado ao objecto de dados de tal forma que se possa usar essa assinatura para verificar a autenticidade e integridade dos dados.Então o que é uma assinatura digital XML (W3C XMLDSIG)? É, como seria de esperar, uma assinatura digital mas adaptada a assinar documentos XML.A forma como funcionam é extremamente fiável.Logo para começar a assinatura não só assegura que a pessoa assinou aquele documento é de facto quem se espera – através de um certificado – como também que o mesmo se manteve inalterado até ao momento em que foi apresentado. Uma mensagem encriptada com uma chave pública apenas pode ser desencriptada com a correspondente chave privada.

Começamos por processar o documento. Para isso precisamos de transformar o ficheiro XML em um ficheiro que seja igual na fonte e no destino. Como sabem em XML ter

<nome>   Nuno Pinto</nome>

É igual a

<nome>Nuno Pinto</nome>

Logo surge a necessidade de criar uma representação única para cada documento XML. A este processo chamamos canonicalização. Numa assinatura digital XML existe a necessidade de explicitamente declarar qual foi o algoritmo usado para criar esta representação. Agora podemos processar o documento XML e criar, através de um algoritmo criptográfico num processo normalmente chamado de digest, uma impressão digital do documento. Em seguida, com a chave privada, encriptamos essa impressão digital e enviamos para o destinatário a nossa assinatura (que contém a chave pública, certificados, impressão digital assinada e os algoritmos que foram usados para o digest e a canonicalização).Ao receber o documento assinado pode-se verificar o resultado do digest do documento (usando os algoritmos contidos na assinatura). Depois podemos desencriptar a impressão digital assinada e comparar os dois valores. Se coincidirem é valido dizer que o documento é autentico e não foi alterado. Fixe!Por fim resta dizer que existem três tripos de assinaturas XMLDSIG.

  1. Detached: O documento XML a ser assinado e a assinatura estão são dois ficheiros distintos, sendo que esta tem uma referência ao documento que se propõe a assinar.
  2. Enveloped: O documento XML e a assinatura surgem no mesmo ficheiro de uma forma sequencial.
  3. Enveloping: O documento e a assinatura estão contidos em um envelope XML.

Se este artigo serviu para vos aguçar o apetite sobre este assunto, podem ler mais sobre o assunto no artigo Programing with Java XML Digital Signature API feito pelo Sean Mullan da Sun.

Diffie-Hellman Java Implementation

Diffie-Hellman is a cryptographic key agreement algorithm that allows two parties that have no prior knowledge of each other to jointly establish a shared secret key over an insecure communications channel. This key can then be used to encrypt subsequent communications using a symmetric key cipher.

We were asked at cryptography classes to develop such algorithm using the core java libraries. I made a little test – I think they call it jUnit – to prove that both famous Bob and infamous Alice share the same dirty little secret.. :)Source: http://nunojobpinto.googlepages.com/diffie-hellman.zip[EDIT: As Ruben pointed out Diffie-Hellman is vulnerable to man-in-the-middle attacks. This is a purely academic work and - despite the brilliance of the response - is not intended to be used as is. If you want to learn more about this maybe you should read about station-to-station and certificates. In Portuguese you can use the resources given to cryptography masters students at University of Minho]Also if your using Netbeans IDE 6 you are probably noticing that the themes SUCK. I don’t even mean this as it’s not eye-candy, I really mean they hurt the eyes and I am already using glasses due to the overwhelming amount of time I spend at my laptop.To surpass this I advise you to download these files:

Now open your very own Netbeans IDE – wait 10 minutes for it to start – and then go to:

  • Tools -> Plugins -> Downloaded -> Add

Now add the two files you have just downloaded and change the theme in Tools -> Preferences and you are ready to go.

Chaos Theory: The Butterfly Effect [Lorenz Attactor]

I was asked to deliver some work on chaos theory and my group choose Lorenz Attractor as object of study. It’s a really nice chaos function as you can learn in the wiki page dedicated to the subject.The work was developed in OpenGL but I’m pretty sure that it would have been easier to do so in PovRay. Ok, bad joke :PI found some useful links for OpenGL Beginners from IST (here) and UMINHO (here). If you are just learning OpenGL give them a look. (Portuguese only, sorry)If you want to give the application a try download the sources at http://nunojobpinto.googlepages.com/isdGL.zip and compile them. You’ll need GCC, build-essentials and – who would of thought? – the OpenGL libraries.It’s all explained in a slightly demented readme file. Have a nice week!

Follow

Get every new post delivered to your Inbox.