<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Stuff… And Things…</title>
	<atom:link href="http://stuff-things.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://stuff-things.net</link>
	<description>Paradise is exactly like where you are right now only much, much better…</description>
	<lastBuildDate>Thu, 03 Jun 2010 00:24:23 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Generating RSA Key Pairs in Ruby</title>
		<link>http://stuff-things.net/2009/12/11/generating-rsa-key-pairs-in-ruby/</link>
		<comments>http://stuff-things.net/2009/12/11/generating-rsa-key-pairs-in-ruby/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 00:49:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://stuff-things.net/?p=82</guid>
		<description><![CDATA[I&#8217;ve given a number of examples of using Public-key cryptography in blog posts and in the Strongbox documentation, but I&#8217;ve always generated the RSA key pair using the openssl command line tool, i.e.
% openssl genrsa -des3 -out private.pem 2048
Generating RSA private key, 2048 bit long modulus
......+++
.+++
e is 65537 (0x10001)
Enter pass phrase for private.pem:
Verifying - Enter pass [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve given a number of examples of using <a href="http://en.wikipedia.org/wiki/Public-key_cryptography" target="_blank">Public-key cryptography</a> in blog posts and in the <a href="http://github.com/spikex/strongbox" target="_blank">Strongbox</a> documentation, but I&#8217;ve always generated the RSA key pair using the openssl command line tool, i.e.</p>
<pre><code>% openssl genrsa -des3 -out private.pem 2048
Generating RSA private key, 2048 bit long modulus
......+++
.+++
e is 65537 (0x10001)
Enter pass phrase for private.pem:
Verifying - Enter pass phrase for private.pem:
% openssl rsa -in private.pem -out public.pem -outform PEM -pubout
% cat private.pem public.pem > key_pair.pem
</code></pre>
<p>This is fine if you want to generate a key pair once, but what if you want to do it on the fly?  The Ruby OpenSSL library has support for generating key pairs:</p>
<p><span style="font-family: Consolas, Monaco, 'Courier New', Courier, monospace; line-height: 18px; font-size: 12px; white-space: pre;">require &#8216;openssl&#8217;</span></p>
<pre class="ruby">rsa_key = OpenSSL::PKey::RSA.new(2048)</pre>
<p>2048 is the key size, and a good value to use for it.</p>
<p>What&#8217;s not obvious is how to encrypt the private key.   You don&#8217;t <strong>have to</strong> encrypt it, but, if you don&#8217;t, anyone who gets a hold of the key can decrypt your data.  Using an unencrypted private key gives you one layer of security (something you have &#8211; the key), encrypting it gives you an additional layer (something you know &#8211; the password).</p>
<p>To encrypt the private key you need a <a href="http://www.ruby-doc.org/ruby-1.9/classes/OpenSSL/Cipher.html" target="_blank">Cipher</a> object:</p>
<pre class="ruby">cipher =  OpenSSL::Cipher::Cipher.new('des3')</pre>
<p>Then, using the Cipher object, you convert the the key_pair to <a href="http://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions" target="_blank">PEM</a> format:</p>
<pre class="ruby">private_key = rsa_key.to_pem(cipher,'password')
public_key = rsa_key.public_key.to_pem
key_pair = private_key + public_key
</pre>
<p>The resulting PEM strings be saved and then later fed to <a href="http://www.ruby-doc.org/ruby-1.9/classes/OpenSSL/PKey/RSA.html#M006380">OpenSSL::PKey::RSA.new()</a> or used with Strongbox.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2009/12/11/generating-rsa-key-pairs-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Compiling Emacs.app on Snow Leopard</title>
		<link>http://stuff-things.net/2009/09/29/emacs-on-snow-leopard/</link>
		<comments>http://stuff-things.net/2009/09/29/emacs-on-snow-leopard/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 20:30:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Emacs]]></category>
		<category><![CDATA[OS X]]></category>

		<guid isPermaLink="false">http://stuff-things.net/?p=75</guid>
		<description><![CDATA[UPDATE: Emacs.app builds fine (and has for a while) as a 64 bit application.
As previous noted, when it comes to Emacs for the Mac, I&#8217;m a fan of Emacs.app.  However, Emacs.app is not quite ready for Snow Leopard&#8217;s 64 bit support.  You must compile it as a 32 bit executable.

cvs -z3 -d:pserver:anonymous@cvs.savannah.gnu.org:/sources/emacs co [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE:</strong> Emacs.app builds fine (and has for a while) as a 64 bit application.</p>
<p><a href="http://stuff-things.net/2009/01/06/emacs-on-the-mac/">As previous noted</a>, when it comes to Emacs for the Mac, I&#8217;m a fan of <a href="http://www.emacswiki.org/emacs/EmacsApp" target="_blank">Emacs.app</a>.  However, Emacs.app is not quite ready for Snow Leopard&#8217;s 64 bit support.  You must compile it as a 32 bit executable.</p>
<p><code><br />
cvs -z3 -d:pserver:anonymous@cvs.savannah.gnu.org:/sources/emacs co emacs<br />
cd emacs<br />
<span style="text-decoration: line-through;"> env CC='gcc -arch i386' ./configure --with-ns</span><br />
<code>./configure --with-ns</code><br />
<code> make<br />
make install  # This builds the .app wrapper, it does not install anything.<br />
</code></code></p>
<p>Then move <em>nextstep/Emacs.app</em> in to <em>/Applications</em>.</p>
<p>The developers have been actively working on Snow Leopard issues; hopefully 64 bit support is not far behind.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2009/09/29/emacs-on-snow-leopard/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pro Git</title>
		<link>http://stuff-things.net/2009/09/02/pro-git/</link>
		<comments>http://stuff-things.net/2009/09/02/pro-git/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 18:19:35 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Git]]></category>
		<category><![CDATA[development]]></category>

		<guid isPermaLink="false">http://stuff-things.net/?p=65</guid>
		<description><![CDATA[Scott Chacon, one of the guys behind GitHub, has released Pro Git, which, as the name suggests, is a new Git book.   He&#8217;s made it available under the Creative Commons Attribution-Non Commercial-Share Alike 3.0 license, which is to say it&#8217;s free.    It cover the basics you&#8217;d except, but really shines when it [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://progit.org/about.html" target="_blank">Scott Chacon</a>, one of <a href="http://logicalawesome.com/" target="_blank">the guys behind GitHub</a>, has released <a href="http://progit.org/" target="_blank">Pro Git</a>, which, as the name suggests, is a new Git book.   He&#8217;s made it available under the <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/us/" target="_blank">Creative Commons Attribution-Non Commercial-Share Alike 3.0</a> license, which is to say it&#8217;s free.    It cover the basics you&#8217;d except, but really shines when it comes to advanced usages, customization,  policy,  hosting,  internals, etc.  It&#8217;s the resource to reach for when it&#8217;s time to loose your amateur status.   And did I mention it&#8217;s free?</p>
<p>You can show your support by <a href="http://tinyurl.com/amazonprogit" target="_blank">buying a print copy</a> (the author&#8217;s link, not mine).</p>
<p>It also plays nicely with <a href="http://fluidapp.com/">Fluid</a>, using <em>http://progit.org/book</em> for the Fluid URL and perhaps picking up an image from <a href="http://tinyurl.com/amazonprogit" target="_blank">Amazon</a> for the icon.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2009/09/02/pro-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>In defense of &#8220;unless&#8221; (in Ruby and elsewhere)</title>
		<link>http://stuff-things.net/2009/08/26/in-defense-of-unless/</link>
		<comments>http://stuff-things.net/2009/08/26/in-defense-of-unless/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 15:58:50 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://stuff-things.net/?p=53</guid>
		<description><![CDATA[I recently came across John Nunemaker&#8217;s take on using &#8220;unless&#8221; in Ruby and thought I&#8217;d share my two cents.
The key to making your code more readable with &#8220;unless&#8221; to is is to think semantics, not syntax.  In spoken languages if there is more that one way to say something, there will be subtle differences [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came across <a href="http://railstips.org/">John Nunemaker&#8217;s</a> take on <a href="http://railstips.org/2008/12/1/unless-the-abused-ruby-conditional">using &#8220;unless&#8221; in Ruby</a> and thought I&#8217;d share my two cents.</p>
<p>The key to making your code more readable with &#8220;unless&#8221; to is is to think semantics, not syntax.  In spoken languages if there is more that one way to say something, there will be subtle differences in meaning.  In English &#8220;unless&#8221; does not mean the same as &#8220;if not&#8221;, instead it indicates an exception or unlikely condition.  For example, compare:</p>
<p><q>Unless it rains, we will go to the park.</q></p>
<p>to</p>
<p><q>If it&#8217;s not raining, we will go to the park.</q></p>
<p>The first sentence suggests that rain is possible, but not likely,  the second that it is likely to be raining.  To get the most out &#8220;unless&#8221; in your code, use it the same way.</p>
<p>John gives this as example of code that&#8217;s very readable with &#8220;unless&#8221;:</p>
<pre>raise InvalidFormat unless AllowedFormats.include?(format)</pre>
<p>Simple, elegant, and anyone reading it will understand that we expect the format to be allowed.  In the unlikely case that the format falls outside of what we expect we raise an exception.  Where as with &#8220;if&#8221;:</p>
<pre>raise InvalidFormat if !AllowedFormats.include?(format)</pre>
<p>is just a little bit ugly and says less about what is expected.</p>
<p>In his post, John argues against using &#8220;if&#8221; with &#8220;else&#8221; but I disagree.  Again, I think in makes for more readable code when you are testing for an unexpected condition.  Consider code that checks for an inactive user:</p>
<pre>unless (@user.inactive?)
   #stuff
else
   redirect_to take_of_you_hoser_url
end</pre>
<p>Reading the code, our expected course of action, doing stuff for the user, comes first, followed by the unlikely case that an inactive user is trying to do stuff.  You could of course write:</p>
<pre>if (@user.active?)</pre>
<p>and there&#8217;s nothing wrong with that.  However, I feel that using &#8220;unless&#8221; makes it clear what is expected.</p>
<p>In short, if you are using &#8220;unless&#8221; as a simple macro for &#8220;if !()&#8221;, then you shouldn&#8217;t be using it at all.  However, &#8220;unless&#8221; is another tool which, when used with care, can make your code clearer.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2009/08/26/in-defense-of-unless/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing Strongbox</title>
		<link>http://stuff-things.net/2009/04/17/introducing-strongbox/</link>
		<comments>http://stuff-things.net/2009/04/17/introducing-strongbox/#comments</comments>
		<pubDate>Fri, 17 Apr 2009 16:49:59 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Active Record]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://stuff-things.net/?p=44</guid>
		<description><![CDATA[Over a year ago I wrote the wildly popular Encrypting Lots of Sensitive Data with Ruby (on Rails).  At the end I said:
Clearly, this screams for a plugin;  watch this space.
Well, it took a while and it turned out to be a gem, but Strongbox has arrived.
First a recap:
You have a web application [...]]]></description>
			<content:encoded><![CDATA[<p>Over a year ago I wrote the wildly popular <a href="http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails">Encrypting Lots of Sensitive Data with Ruby (on Rails)</a>.  At the end I said:</p>
<blockquote><p>Clearly, this screams for a plugin;  watch this space.</p></blockquote>
<p>Well, it took a while and it turned out to be a gem, but <strong><a href="http://github.com/spikex/strongbox">Strongbox</a></strong> has arrived.</p>
<p>First a recap:</p>
<p>You have a web application and you need to encrypt the data your receive from your users.   The most common form of encryption is <a href="http://en.wikipedia.org/wiki/Symmetric_cryptography">symmetric-key encryption</a>, where one password is used for both encryption and decryption.  This works very well, but it means that everyone who enters data needs to know the password and everyone who knows the password can decrypt the data.</p>
<p>Enter <a href="http://en.wikipedia.org/wiki/Public-key_cryptography">Public-key cryptography</a> which used one password (key) to encrypt and a different key to decrypt.   This solves the problem; make the encryption password, the public key, available to your application, and keep  the decryption password, the private key, well, private.  Users don&#8217;t need to know or care how, they fill out a form and the data gets encrypted.  One small problem, size.  The most you can practically encrypt using this method is 245 bytes.  Good enough for the launch codes, but not so for driving directions to the buried treasure.</p>
<p>No problem, if we have larger data, we simply combine the two.  We generate a random password and use it to symmetrically encrypt to data.  We then use the public key to encrypt the random password.  To get the data back, the private key is used to decrypt the random password which is in turn used to decrypt the original data.</p>
<p>Got it?  Good. <a href="http://github.com/spikex/strongbox">Strongbox</a> takes the above three paragraphs and reduces them to this:</p>
<pre>class User &lt; ActiveRecord::Base
  encrypt_with_public_key :secret,
                          :key_pair =&gt; 'path/to/keypair.pem'
end

&gt;&gt; @user = User.new
&gt;&gt; @user.secret = 'Ssssh'
&gt;&gt; @user.secret  # =&gt; "*encrypted*"
&gt;&gt; user.secret.decrypt ‘letmein’ # =&gt; "Ssssh"</pre>
<p>OK, it&#8217;s sightly more complex.   The column &#8220;secret&#8221; needs to exist in the database and be type &#8220;binary&#8221; (more on this in a bit).  In additional, because we are using symmetric encryption (the default), we need two binary columns &#8220;secret_key&#8221; and &#8220;secret_iv&#8221; to store the generated symmetric key and <a href="http://en.wikipedia.org/wiki/Initialization_vector">Initialization vector (IV)</a> (which you can think of as a second key (but it&#8217;s <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation">not</a>) once they are encrypted with the public key.</p>
<p>If you are certain that the data you are encrypting won&#8217;t be larger than 245 bytes, you can use the following:</p>
<pre>class User &lt; ActiveRecord::Base
  encrypt_with_public_key :secret,
                          :key_pair =&gt; 'path/to/keypair.pem',
                          :symmetric =&gt; :never
  validates_length_of :secret, :maximum=&gt; 245
end</pre>
<p>This skips the symmetric encryption, is faster, and you only need the binary &#8220;secret&#8221; column.</p>
<p>You&#8217;ll also need to generate a key pair.  Be sure to choose a strong pass phrase, as this is the one that will decrypt everything (as always, I suggest using <a href="http://world.std.com/~reinhold/diceware.html">Diceware</a>).</p>
<pre><code>
% openssl genrsa -des3 -out private.pem 2048
Generating RSA private key, 2048 bit long modulus
......+++
.+++
e is 65537 (0x10001)
Enter pass phrase for key_pair.pem:
Verifying - Enter pass phrase for key_pair.pem:
</code></pre>
<p>If you aren&#8217;t going to be decrypting data on a regular basis you might want to deploy just the public key.  Extract it:</p>
<pre><code>
mv key_pair.pem private.pem
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
Enter pass phrase for private.pem:
writing RSA key
</code></pre>
<p>And change your model:</p>
<pre>class User &lt; ActiveRecord::Base
  encrypt_with_public_key :secret,
                          :public_key =&gt; 'path/to/public.pem'
                          :private_key =&gt; 'path/to/private.pem'
end</pre>
<p>You could then have rake/Capistrano task to deploy and remove the private key as needed.  Or you could limit it&#8217;s use to a separate, non-public, server.</p>
<p>As noted  above you want your database column(s) to be binary.  If your database does not have a binary type you can add the <em>:base64</em> option:</p>
<pre>class User &lt; ActiveRecord::Base
  encrypt_with_public_key :secret,
                          :key_pair =&gt; 'path/to/keypair.pem',
                          :base64 =&gt; :true
end</pre>
<p>This will convert the binary data to text using Base64.  You must, <strong>must</strong> make your column type &#8220;text&#8221;.   Base64 increases the length of the data it encodes by approximately 137%.  Type &#8220;string&#8221; is typically 256 bytes, 245 * 1.37 = 335.65 bytes.   <em>If you use a &#8220;string&#8221; column and encrypt anything greater than 186 bytes <strong>your data will be lost</strong></em>.</p>
<p>Finally, there are two addition options for tweaking the encryption settings that you are unlikely to need:</p>
<p>&#8220;:symmetric_cipher&#8221; lets you change the algorithm that&#8217;s used for symmetric encryption.  The default is 256 bit <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">Advanced Encryption Standard</a> (AES) using  <a href="http://en.wikipedia.org/wiki/Cipher_block_chaining">Cipher Block Chaining</a> (CBC) (&#8216;aes-256-cbc&#8217; in OpenSSL terms).   AES has been approved by the NSA for top secret information, so it&#8217;s probably good enough, but <a href="http://en.wikipedia.org/wiki/Blowfish_(cipher)">Blowfish</a> (&#8216;bf-cbc&#8217;) is know to work as well.  <a href="http://www.openssl.org/docs/apps/enc.html">Other ciphers in CBC mode</a> should also work, but have not been tested by me.  (Note that all ciphers may not be supported by your version of OpenSSL, &#8220;openssl list-cipher-commands&#8221; will provide a list.)</p>
<p>&#8220;:padding&#8221; allows you to change the method used to pad data encrypted with the public key.   Unless you are working with legacy data, you shouldn&#8217;t need to change this.  The default is &#8220;RSA_PKCS1_PADDING&#8221;, see the code if you need other options.</p>
<p><strong>Disclaimer</strong></p>
<p>I am not a security expert.  This software using an off the shelf encryption tool, namely <a href="http://www.openssl.org/">OpenSSL</a>, that has been well tested, but that is not a guarantee that this implementation doesn&#8217;t have weakness.  Be sure you understand what <em>Strongbox</em> does, and review it for your application.  A few things to keep in mind:</p>
<ul>
<li><em>Strongbox</em> encrypts the data as it is saved, but no sooner.  Be sure to use HTTPS for submitting the forms (and decrypting data!).</li>
<li>If an attacker gains entry to your system the encryption should protect your data.   However, they might be able to hack your code to intercept new data or, much worse, your private key password.  Protect your server.</li>
<li>When decrypting make sure your data isn&#8217;t cached.</li>
</ul>
<p>And test, test, test.  If there is a problem with how your data is encrypted, there is no getting it back.</p>
<p>One concern I have is garbage collection.  If you decrypt something into a variable which then goes out of scope, how long does it hang around in memory?  Can you force it out?  I haven&#8217;t found much information on this; if there are any Ruby GC experts out there, share your knowledge!</p>
<p>I am always open to suggestions and improvement, but, to quote the License:</p>
<blockquote><p>THE SOFTWARE IS PROVIDED &#8220;AS IS&#8221;, WITHOUT WARRANTY OF ANY<br />
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE<br />
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR<br />
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br />
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,<br />
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF<br />
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN<br />
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER<br />
DEALINGS IN THE SOFTWARE.</p></blockquote>
<p>So there!</p>
<p>Finally, I&#8217;d like to give a shout-out to <a href="http://www.thoughtbot.com/">thoughtbot</a>.    While this software has existed for many years, the final form of the gem was greatly inspired by <a href="http://www.thoughtbot.com/projects/paperclip">Paperclip</a>.   It&#8217;s a nice example of an approach to adding complex features to an ActiveRecord attribute and how to test them.   In additional, the gem sat unpublished for nearly a year because it needed test coverage and my testing was week.  Then I took thoughtbot&#8217;s <a href="http://www.thoughtbot.com/services/training/advanced-ruby-on-rails-boston">Advanced Ruby on Rails</a> class which really helped me get my head around testing and TDD, and got this moving again.  If you know Rails, but need to improve your processes, I highly recommend this class.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2009/04/17/introducing-strongbox/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Emacs on the Mac (Life has a funny way of sneaking up on you)</title>
		<link>http://stuff-things.net/2009/01/06/emacs-on-the-mac/</link>
		<comments>http://stuff-things.net/2009/01/06/emacs-on-the-mac/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 22:53:05 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Emacs]]></category>
		<category><![CDATA[OS X]]></category>

		<guid isPermaLink="false">http://stuff-things.net/?p=15</guid>
		<description><![CDATA[I&#8217;ve been using Emacs for more than 20 years now.   I still use it just about everyday on servers I admin.   However, a year or so ago I started using TextMate as my day to day editor for development on the Mac.  TextMate has some nice features:  a very [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using Emacs for more than 20 years now.   I still use it just about everyday on servers I admin.   However, a year or so ago I started using <a href="http://macromates.com/">TextMate</a> as my day to day editor for development on the Mac.  TextMate has some nice features:  a very usable project mode, code snippets, variable completion (Emacs has these as well, but that&#8217;s another post), and it&#8217;s what all of the cool kids were using.</p>
<p>Now all of a sudden <a href="http://search.twitter.com/search?q=emacs+textmate">Emacs</a> <a href="http://peepcode.com/products/meet-emacs">is</a> <a href="http://nubyonrails.com/articles/emacs-emacs">cool</a> <a href="http://xkcd.com/378/">again</a>.   And isn&#8217;t it ironic&#8230;dontcha think?</p>
<p>So, I&#8217;m going to give Emacs on the Mac another shot.  Not (just) to be cool, but because I can&#8217;t so much as type this post without trying to use Emacs key strokes that may not be there (curse you Wordpress  for taking my Control-A!).</p>
<p>In the future I plan to look for Emacs equivalents for TextMate features I&#8217;ll miss. But the first question I need to answer is &#8220;Which Emacs to use?&#8221;  There are a number of options, all with pluses and minuses.   Since I couldn&#8217;t find much in the way of comparisons, I thought I&#8217;d better review them myself.  I&#8217;ve limited this to native OS X ports of <a href="http://www.gnu.org/software/emacs/">GNU Emacs</a>.  There also exists <a href="http://www.emacswiki.org/emacs/XEmacs">XEmacs</a>, a major fork of GNU Emacs with <a href="http://members.shaw.ca/akochoi-xemacs/">Mac support</a> but I&#8217;m not an XEmacs user.  And it&#8217;s possible to run X Windows versions of Emacs under OS X, but if that&#8217;s your thing, you don&#8217;t need my help setting it up.</p>
<p>The <a href="http://www.emacswiki.org">EmacsWiki</a> offers a lot of <a href="http://www.emacswiki.org/emacs/EmacsForMacOS">Mac Options</a>, but it really boils down to three choices:  <em>Aquamacs</em>, <em>Carbon Emacs</em>, and <em>Emacs.App</em>.  These native versions of Emacs do have a lot in common.  They:</p>
<ul>
<li>Are GUI based. (You may have only seen console versions of Emacs but it&#8217;s had a GUI for at least 15 years.)</li>
<li>Support common Command/Apple key bindings, so you can save files with Command-S instead of C-x C-s, open files with Command-O, cut and paste with Command-C and Command-V, and so on.</li>
<li>Are integrated with the system cut buffer; if you copy, or kill (cut) text in using Emacs commands, it will be available to paste in other applications.  Likewise, text copied or cut in other applications can be pasted into Emacs using it&#8217;s yank (paste) commands.</li>
<li>Follow the X-Windows style of copy on select, paste on middle-button</li>
</ul>
<p><strong>Aquamacs</strong></p>
<p><a href="http://aquamacs.org/">Aquamacs</a> is the most Mac like Emacs of the bunch.  The Aquamacs developers strive to give Emacs a Mac feel.  It features customizations such as a Mac-style tool bar, user friendly menus, and, in the <a href="http://sourceforge.net/forum/forum.php?forum_id=902370">1.6 preview version</a>, tabbed buffers.   When using the Command/Apple keys to open or save files it uses the standard file dialogs.  The distribution also includes a large number of add-on editing modes and packages, many of which have been pre-configured.</p>
<p>One oddity is it&#8217;s printing support,  it sends the buffer to Preview for printing.</p>
<p>If you are new to the Emacs, then Aquamacs is probably the place to start.   However, if you&#8217;ve used Emacs previously you may find that some Emacs-ness has been lost, and if you plan to use Emacs on other platforms you may find some of the differences confusing.</p>
<p><a href="http://aquamacs.org/cgi-bin/download.cgi">Download Aquamacs</a><br />
<a href="http://www.emacswiki.org/cgi-bin/wiki/AquamacsEmacs/">Aquamacs FAQ</a></p>
<p><strong>Carbon Emacs</strong></p>
<p>Interestingly, while not the official version, out of the box <a href="http://homepage.mac.com/zenitani/emacs-e.html">Carbon Emacs</a> is Emacs to a fault; by default standard Mac key-binding are not enabled and the Command/Apple key is the meta-key.  This is, in fact, the version of Emacs that ships with OS X 10.5 Leopard and is installed in &#8220;/usr/bin/emacs&#8221;.   Apple does not include the .app wrapper so it only runs in the command line.   In theory you could download and install just the wrapper, but it&#8217;s much easier to grab the full version from <a href="http://www.apple.com/downloads/macosx/unix_open_source/carbonemacspackage.html">Apple</a></p>
<p>To make it more Mac like add:</p>
<p><code><br />
(mac-key-mode 1)<br />
(setq mac-option-modifier 'meta)<br />
</code></p>
<p>to your .emacs.el  which will enable the standard Command/Apple key bindings and make the Alt/Option key the meta key.  Thus configured it strikes a good balance between being Emacs and being a Mac application.</p>
<p>Like Aquamacs,  Carbon Emacs ships with additional pre-configured editing modes and packages.   Unlike Aquamacs it doesn&#8217;t add much in the way of Mac-ish features.  It also has the best printing support, being the only one of the three to use the native print dialog.  Carbon Emacs is actively developed, but, because of the time needed to integrate it&#8217;s changes, it may lag a bit behind the official version.</p>
<p>Carbon Emacs is a good choice for people who want a &#8220;standard&#8221; Emacs with a Mac feel to it and a good collection of pre-configured add-ons.</p>
<p><a href="http://www.apple.com/downloads/macosx/unix_open_source/carbonemacspackage.html">Download Carbon Emacs</a><br />
<a href="http://homepage.mac.com/zenitani/emacs-e.html">Carbon Homepage</a></p>
<p><strong>Emacs.App</strong></p>
<p>Emacs.App (or EmacsApp) is the official version of Gnu Emacs for the Mac.   It&#8217;s based on the NeXTstep / OpenStep / Cocoa API and is very similar in look and feel to Carbon Emacs.  Naturally it only includes the standard packages and modes that come with official versions of Emacs.</p>
<p>The major downside is that Emacs.App is not in the current stable Emacs release (22.3).  It will be included in Emacs 23, due (or predicted for) later in 2009, but until then it only available in the developer “edge” version through CVS.   This creates a further issue in that, while there are binary distributions available they tend to be out of date, so you&#8217;ll have to build it from source.  Fortunately this is very straight forward:<br />
<code><br />
cvs -z3 -d:pserver:anonymous@cvs.savannah.gnu.org:/sources/emacs co emacs<br />
cd emacs<br />
./configure --with-ns<br />
make<br />
make install<br />
cp nextstep/Emacs.app /Applications<br />
</code><br />
(The &#8220;make install&#8221; step builds the .app wrapper, it doesn&#8217;t actually install anything.)</p>
<p>Emacs.app is also available from MacPorts and Fink.</p>
<p>When all is said and done Emacs.App <em>is</em> Emacs; if you want to be be up to date with the current version, then this is the one to use.  However, you will need to install, configure, and maintain any additional modes and packages you want to use.</p>
<p><a href="http://www.emacswiki.org/emacs/EmacsApp">Emacs.app at the EmacsWiki</a></p>
<p>In short, choose Aquamacs if you want a more Mac-Like Emacs.   For the Emacs experience with less effort, use Carbon Emacs.  For the most current Emacs, with all of the risks and rewards of using edge software, plus a little more work, use Emacs.App.</p>
<p>Myself, I&#8217;m going to go with Emacs.App.   It&#8217;s closest to the versions I use on my servers, willing to beta-test, and I&#8217;m comfortable installing and configuring additional packages.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2009/01/06/emacs-on-the-mac/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dealing with read-only fields and partial updates in Rails 1.x</title>
		<link>http://stuff-things.net/2008/09/03/dealing-with-read-only-fields-and-partial-updates-in-rails-1x/</link>
		<comments>http://stuff-things.net/2008/09/03/dealing-with-read-only-fields-and-partial-updates-in-rails-1x/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 16:35:03 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Active Record]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://stuff-things.net/2008/09/03/dealing-with-read-only-fields-and-partial-updates-in-rails-1x/</guid>
		<description><![CDATA[So, you have a column in your database you can&#8217;t update after the record is created.   Not don&#8217;t want to update, but can&#8217;t.  Specifically, you might have a column that is protected by a trigger, which will cause an error if that column is included in a update.  How do you [...]]]></description>
			<content:encoded><![CDATA[<p>So, you have a column in your database you can&#8217;t update after the record is created.   Not <em>don&#8217;t want</em> to update, but <em>can&#8217;t</em>.  Specifically, you might have a column that is protected by a trigger, which will cause an error if that column is included in a update.  How do you prevent ActiveRecord from trying to update that column?</p>
<p>Prior to Rails 2.0, ActiveRecord will always generate an SQL UPDATE statement that includes all of the attributes in the model, even if they hadn&#8217;t changed.</p>
<pre name="code" class="ruby">
product = Product.find(:first)
=&gt; #&lt;Product:0x23a7d00 @attributes={"name"=&gt;"Product", "description"=&gt;"Lorem ipsum",  "price"=&gt;"9.99", "sku" =&gt; "000001"}&gt;
# Inflation
product.price += 1.00.to_d # You're not using floats for prices, are you?
product.save

=&gt; UPDATE products SET `price` = '10.99', `available` = 1, `description` = 'Lorem ipsum',  `name` = 'Product', `sku` = '000001' WHERE `id` = 1
</pre>
<p>If &#8220;sku&#8221; happens to be read-only, the update will fail, and so will your app.</p>
<p>The <em>right</em> way to fix this is to upgrade to Rails 2.x.   Starting 2.0 you can use attr_readonly which (silently) removes the attribute from the UPDATE statement.</p>
<pre name="code" class="ruby">
attr_readonly :sku
product = Product.find(:first)
=&gt; #&lt;Product:0x23a7d00 @attributes={"name"=&gt;"Product", "description"=&gt;"Lorem ipsum",  "price"=&gt;"9.99", "sku" =&gt; "000001"}&gt;
product.price += 1.00.to_d
product.save

=&gt; UPDATE products SET `price` = '10.99', `available` = 1, `description` = 'Lorem ipsum',  `name` = 'Product' WHERE `id` = 1
</pre>
<p>And, starting with 2.1, ActiveRecord only updates attributes that have been changed.  As long as you don&#8217;t change the value of an attribute, it won&#8217;t be included in the UPDATE statement.</p>
<pre name="code" class="ruby">
product = Product.find(:first)
=&gt; #&lt;Product:0x23a7d00 @attributes={"name"=&gt;"Product", "description"=&gt;"Lorem ipsum",  "price"=&gt;"9.99", "sku" =&gt; "000001"}&gt;
product.price  += 1.00.to_d
product.save

=&gt; UPDATE `products` SET `price` = '10.99'  WHERE `id` = 1
</pre>
<p>(Obviously, it&#8217;s better to explicitly mark an attribute as read-only then to depend on this behavior.)</p>
<p>But, what if you are working with a pre 2.X version of Rail?   As I said above, ActiveRecord generates the UPDATE statement based on the attributes in the model.  The trick, or should I say ugly hack, is to load the record with only the fields you want to update using <em>:select</em>.  This way, when the UPDATE is generate it will only include those attributes that were loaded into the record.</p>
<pre name="code" class="ruby">
product = Product.find(:first, :select =&gt; 'id, name, price')
=&gt; #&lt;Product:0x23a7d00 @attributes={"name"=&gt;"Product", "price"=&gt;"9.99", "id"=&gt;"1"}&gt;
product.price  += 1.00.to_d
product.save

=&gt; UPDATE `products` SET `price` = '10.99',   `name` = 'Product' WHERE `id` = 1
</pre>
<p>When doing this, you need to include the &#8220;id&#8221; column (or whatever your primary key is) in the select.   Also note that while this will work with find_by_ methods, find_or_initialize_by_ methods do not take the <em>:select</em> option.</p>
<p>Yup, it&#8217;s ugly but, it does, in fact, work.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2008/09/03/dealing-with-read-only-fields-and-partial-updates-in-rails-1x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick and Dirty cropping images with attachment_fu</title>
		<link>http://stuff-things.net/2008/02/21/quick-and-dirty-cropping-images-with-attachment_fu/</link>
		<comments>http://stuff-things.net/2008/02/21/quick-and-dirty-cropping-images-with-attachment_fu/#comments</comments>
		<pubDate>Fri, 22 Feb 2008 03:30:55 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Active Record]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://stuff-things.net/2008/02/21/quick-and-dirty-cropping-images-with-attachment_fu/</guid>
		<description><![CDATA[Rick Olson&#8217;s attachment_fu is a great plugin for attaching files documents to Rails models.  It&#8217;s a rewrite of his acts_as_attachment plugin.  While it can handle any kind of file data, most commonly, it is used for attaching images; as a result attachment_fu handles automatic resizing of images, and creation of thumbnails using RMagick, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://techno-weenie.net/">Rick Olson&#8217;s</a> <a href="http://clarkware.com/cgi/blosxom/2007/02/24">attachment_fu</a> is a great plugin for attaching files documents to Rails models.  It&#8217;s a rewrite of his <a href="http://technoweenie.stikipad.com/plugins/show/Acts+as+Attachment">acts_as_attachment</a> plugin.  While it can handle any kind of file data, most commonly, it is used for attaching images; as a result attachment_fu handles automatic resizing of images, and creation of thumbnails using <a href="http://rmagick.rubyforge.org/">RMagick</a>, <a href="http://rubyforge.org/projects/mini-magick/">minimagick</a>, or <a href="http://seattlerb.rubyforge.org/ImageScience.html">ImageScience</a>.</p>
<p>For example:</p>
<pre name="code" class="ruby">
class ProductImage  &lt; ActiveRecord::Base
  belongs_to :product
  has_attachment :content_type =&gt; :image,
                 :storage =&gt; :file_system,
                 :path_prefix =&gt; '/public/images/products/',
                 :resize_to =&gt; '300',
                 :thumbnails =&gt; {:thumb =&gt; '75x75' }

  validates_as_attachment
end
</pre>
<p>The above will take an image, resize it to 300 pixels wide (automatically adjusting the height to preserve the original images aspect ratio),  and to 75 by 75 pixels for a thumbnail, and save resulting images.  Combined with a Product model that <em>has_one :image</em>, or <em>has_many :images</em>, and the right form, you can easily manage your product images.</p>
<p>However, an image with both a fixed width, and fixed height, like our thumbnail,  can be a problem. If the original, and resized image do not have the same aspect ratio the resized image will be distorted.   In this case, if the original is not square, our thumbnail will be look squished in which ever dimension was longer originally.  This is not a problem for the main image because we let the height be calculated automatically.</p>
<p>Fortunately, there is a simple trick that allows us to override the method attachment_fu uses to resize image and manipulate it ourselves.  Add the following to the ProductImage model:</p>
<pre name="code" class="ruby">
  protected

  # Override image resizing method
  def resize_image(img, size)
    # resize_image take size in a number of formats, we just want
    # Strings in the form of "crop: WxH"
    if (size.is_a?(String) &amp;&amp; size =~ /^crop: (\\d*)x(\\d*)/i) ||
        (size.is_a?(Array) &amp;&amp; size.first.is_a?(String) &amp;&amp;
          size.first =~ /^crop: (\\d*)x(\\d*)/i)
      img.crop_resized!($1.to_i, $2.to_i)
      # We need to save the resized image in the same way the
      # orignal does.
      self.temp_path = write_to_temp_file(img.to_blob)
    else
      super # Otherwise let attachment_fu handle it
    end
  end
</pre>
<p>and change the thumbnail size to:</p>
<pre>
<code>
:thumbnails =&gt; {:thumb =&gt; 'crop: 75x75' }
</code>
</pre>
<p>Now, if the image size starts with &#8216;crop: &#8216;, the image will be resized and then cropped to fit.  Otherwise, it&#8217;s passed on to attachment_fu and handed normally.   I&#8217;m using the RMagic <a href="http://www.imagemagick.org/RMagick/doc/image1.html#crop_resized_bang">crop_resized!</a> method, which resize the image using the smaller dimension and then crops the large one to fit.    If you are using minimagick, or ImageScience you may need to fiddle a bit with the code.  Obviously, you can extend this approach to manipulate the image anyway you see fit.   For example you could automatically put a border on the images:</p>
<pre name="code" class="ruby">
  def resize_image(img, size)
    # Add a 2x2 red border and pass the image to attachment_fu
    img.border!(2,2,'red')
    super
  end
</pre>
<p>Or blur them:</p>
<pre name="code" class="ruby">
  def resize_image(img, size)
    img = img.blur_image
    super # Pass the blured image to attachment_fu
  end
</pre>
<p>Or any other weirdness your heart desires.  Have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2008/02/21/quick-and-dirty-cropping-images-with-attachment_fu/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Encrypting Lots of Sensitive Data with Ruby (on Rails)</title>
		<link>http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/</link>
		<comments>http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/#comments</comments>
		<pubDate>Tue, 05 Feb 2008 18:26:10 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/</guid>
		<description><![CDATA[Previously I wrote about how to use public key encryption to automatically encrypt data using Ruby (and thus Rails).  Because this method can encrypt data without a password, it&#8217;s very useful for securing information received from a form, without the person entering the from having to do anything special.   However public key [...]]]></description>
			<content:encoded><![CDATA[<p>Previously I wrote about how to use public key encryption to automatically encrypt data using Ruby (and thus Rails).  Because this method can encrypt data without a password, it&#8217;s very useful for securing information received from a form, without the person entering the from having to do anything special.   However public key encryption has limits; the amount of data you can encrypt with this method is limited by the key size you use, and, that after a point increasing the key size isn&#8217;t a practical an option.  We solve this problem using a combination of public key encryption and <a href="http://en.wikipedia.org/wiki/Symmetric_cryptography">symmetric-key encryption</a>.</p>
<p>First a little theory; and when I say &#8220;a little&#8221; I mean it.  Under the hood encryption is a headache inducing branch of mathematics.  If you want to the literal truth, there is plenty of good reading out there.</p>
<p>Symmetric-key cryptography is what people tend to think of when, and if, they think of encryption.  A password is used to encrypt some information, and that same password must be entered to retrieve the information.  Under the hood is an algorithm or <em>cipher</em>, which simply put, is a mathematical function that transforms the data into something obscure and then back again.  For our purpose we need a <a href="http://en.wikipedia.org/wiki/Block_cipher">block ciphers</a>.<br />
A block cipher takes a small, typically 128 or 256 bit, chunk of data and encrypts it.  There are many, but in this example we&#8217;ll use the <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">Advanced Encryption Standard</a> which is the de facto standard.</p>
<p>(There also exist <a href="http://en.wikipedia.org/wiki/Stream_cipher">stream ciphers</a> which work on streams of data, encrypting a phone call for example, but that trade security for speed and can be difficult to use correctly.)</p>
<p>We also need a little glue.  Because block ciphers operate on small chunks of data, they need to be applied again and again.   However give the same input data the cipher will always produce the same encrypted output;  any redundancies in the input will be exposed as redundancies  in the output and make in vulnerable to a number of attacks.  To avoid this we use a <em>mode of operation</em> called <a href="http://en.wikipedia.org/wiki/Cipher_block_chaining">Cipher Block Chaining</a>.  CBC using data from one block to further obfuscate the data in the next, effectively hiding any redundancies.</p>
<p>While simple and secure, using symmetric-key cryptography can be problematic; everyone needs to know the password to encrypt data and everyone who has the password (or as the pros say, <em>shared secret key</em>) can decrypt data.   This works well if you small set of people who need to know the password and a secure way to distribute it (over drinks in a dark corner of a seedy bar is poetic, if not necessarily secure) but in the case of a web site with hundreds or thousands of people entering data, it&#8217;s not practical.</p>
<p><a href="http://en.wikipedia.org/wiki/Public-key_cryptography">Public-key cryptography</a> can be thought of as Symmetric-key encryption with two passwords, or keys, called a <em>key pair</em>.  One, the <em>public key</em>, that encrypts data and another, <em>the private key</em> that decrypts.   Because the public key can not be used to decrypt data it encrypts it can be safely given out or installed on a web site, allowing anyone to encrypt data to be sent to the owner of the key.  The private key is kept safe and is typically symmetric encrypted with an additional password</p>
<p>The solution is actually quite simple.  We generate a random password and use that for the symmetric-key encryption.  We then encrypt the random password using the public key, and store both the encrypted password, and encrypted data.   When we need to get at the data, we use the private key, and its password to decrypt the random password which, in turn, is used to decrypt the data.</p>
<p>Well, it&#8217;s almost that simple.  In order to randomize the data, the CBC <em>glue</em> requires a <a href="http://en.wikipedia.org/wiki/Initialization_vector">Initialization vector (IV)</a>.  This <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation">article</a> has a good explanation of why, but for our purposes we can just think of it as a second random password we need to encrypt and save.</p>
<p>OK, enough talk, let&#8217;s  encrypt some text:</p>
<pre name="code" class="ruby">
# OpenSSL provides both symmetric and public key encryption
require 'openssl'

# Encrypt with 256 bit AES with CBC
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt # We are encypting
# The OpenSSL library will generate random keys and IVs
cipher.key = random_key = cipher.random_key
cipher.iv = random_iv = cipher.random_iv

encrypted_data = cipher.update(plain_data) # Encrypt the data.
encrypted_data &lt;&lt; cipher.final
</pre>
<p>At this point we could just save <em>encrypted_data</em> in the database and it would be well protected.  So well in fact that we couldn&#8217;t get it back.  To do that we&#8217;re going to need to save the random password and IV.</p>
<p>Generate a key pair.  Be sure to choose a good password as this is the one that will decrypt everything.</p>
<pre>
<code>
% openssl genrsa -des3 -out private.pem 2048
Generating RSA private key, 2048 bit long modulus
......+++
.+++
e is 65537 (0x10001)
Enter pass phrase for private.pem:
Verifying - Enter pass phrase for private.pem:
</code>
</pre>
<p>Now extract the public key:</p>
<pre>
<code>
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
Enter pass phrase for private.pem:
writing RSA key
</code>
</pre>
<p>See my <a href="http://stuff-things.net/2007/06/11/encrypting-sensitive-data-with-ruby-on-rails/">previous article</a> for more details on what we&#8217;re doing here.</p>
<p>Now we can use the public key to encrypt the random key and IV:</p>
<pre name="code" class="ruby" width="800">
public_key_file = 'public.pem';

public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file))

encrypted_key = public_key.public_encrypt(random_key)
encrypted_iv = public_key.public_encrypt(random_iv)
</pre>
<p>Now if we store all three pieces,  <em>encrypted_key</em>, <em>encrypted_iv</em>,  and <em>encrypted_data</em> we have successfully encrypted our original data.</p>
<p>Of course we&#8217;ll want to get that data back, and to do so we reverse the process:</p>
<pre name="code" class="ruby" width="800">
require 'openssl'

private_key_file = 'private.pem';

private_key =
   OpenSSL::PKey::RSA.new(File.read(private_key_file),password)

cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.decrypt
cipher.key = private_key.private_decrypt(encrypted_key)
cipher.iv = private_key.private_decrypt(encrypted_iv)

decrypted_data = cipher.update(encrypted_data)
decrypted_data &lt;&lt; cipher.final
</pre>
<p><em>password</em> is the password you used when generating the key-pair.</p>
<p>Now let&#8217;s put it all together in an Active Record model:</p>
<pre name="code" class="ruby" width="800">
class Sensitive &lt; ActiveRecord::Base

  attr_accessor :plain_data
  attr_protected :encrypted_data, :encrypted_key, :encrypted_iv
  before_save :encrypt_sensitive

  def decrypt_sensitive(password)
    if self.encrypted_data
      private_key = OpenSSL::PKey::RSA.new(File.read(APP_CONFIG['private_key']),password)
      cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
      cipher.decrypt
      cipher.key = private_key.private_decrypt(self.encrypted_key)
      cipher.iv = private_key.private_decrypt(self.encrypted_iv)

      decrypted_data = cipher.update(self.encrypted_data)
      decrypted_data &lt;&lt; cipher.final
    else
      ''
    end
  end

  def clear_sensitive
    self.encrypted_data = self.encrypted_key = self.encrypted_iv = nil
  end

  private

  def encrypt_sensitive
    if !self.plain_data.blank?
      public_key = OpenSSL::PKey::RSA.new(File.read(APP_CONFIG['public_key']))
      cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
      cipher.encrypt
      cipher.key = random_key = cipher.random_key
      cipher.iv = random_iv = cipher.random_iv

      self.encrypted_data = cipher.update(self.plain_data)
      self.encrypted_data &lt;&lt; cipher.final

      self.encrypted_key =  public_key.public_encrypt(random_key)
      self.encrypted_iv = public_key.public_encrypt(random_iv)
    end
  end
end
</pre>
<p>When creating or updating your model you don&#8217;t have to do anything, if &#8220;plain_data&#8221; is present it will be automatically encrypted.  When you want to view the plain text you call &#8220;@record.decrypt_sensitive(&#8216;passwd&#8217;)&#8221;; that could be done with a little AJAX that prompts for a password and populates the &#8220;plain_data&#8221; field.  The encrypted data is only updated when &#8220;plain_data&#8221; is present.  This done so that the record can be updated without decrypting (and re-encrypting) encrypted data (handy in an application were not everyone has access to the sensitive data).  To actually clear the   encrypted data call &#8220;@record.clear_sensitive&#8221; and then save.</p>
<p>Setting up the APP_CONFIG hash is left as an exercise for the reader.</p>
<p>Clearly, this screams for a plugin;  watch this space.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Encrypting Sensitive Data with Ruby (on Rails)</title>
		<link>http://stuff-things.net/2007/06/11/encrypting-sensitive-data-with-ruby-on-rails/</link>
		<comments>http://stuff-things.net/2007/06/11/encrypting-sensitive-data-with-ruby-on-rails/#comments</comments>
		<pubDate>Mon, 11 Jun 2007 17:02:08 +0000</pubDate>
		<dc:creator>Spike</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://stuff-things.net/2007/06/11/encrypting-sensitive-data-with-ruby-on-rails/</guid>
		<description><![CDATA[In Encrypting Sensitive Data with Perl I wrote about how to use public key encryption to automatically and securely encrypt information with Perl.  This allows you encryption things like credit card numbers, bank routing information, or that winning PowerBall number in a unattended fashion.   Typically, you would use this in a situation [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://stuff-things.net/2007/05/02/encrypting-sensitive-data-with-perl/">Encrypting Sensitive Data with Perl</a> I wrote about how to use <a href="http://en.wikipedia.org/wiki/Public-key_cryptography">public key encryption</a> to automatically and securely encrypt information with Perl.  This allows you encryption things like credit card numbers, bank routing information, or that winning PowerBall number in a unattended fashion.   Typically, you would use this in a situation where a user needs to enter sensitive information into a form which need to be stored in a secure manner.   We can do this with Ruby (on Rails) as well, and it&#8217;s even easier.</p>
<p>First we need to generate a key pair.  This creates two keys, a public key which will only be used to encrypt data, and a private key, which will only be used to decrypt data.  The private key is protected by a password know only to us.  When it comes to choosing strong passwords, I suggest using <a href="http://world.std.com/~reinhold/diceware.html">Diceware</a>.  <em>2048</em> is the key size in bits.  Bigger is better, but also slower;  2048 is considered a good trade off between speed and encryption strength.  We are also limited by this to encrypting as most 2048 bits, more on this below.</p>
<pre>
<code>
% openssl genrsa -des3 -out private.pem 2048
Generating RSA private key, 2048 bit long modulus
......+++
.+++
e is 65537 (0x10001)
Enter pass phrase for private.pem:
Verifying - Enter pass phrase for private.pem:
</code>
</pre>
<p>Then we extract the public key:</p>
<pre>
<code>
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
Enter pass phrase for private.pem:
writing RSA key
</code>
</pre>
<p>Once we have the keys, we can encrypt data using the following:</p>
<pre name="code" class="ruby">
#!/usr/bin/env ruby

require 'openssl'
require 'base64'

public_key_file = 'public.pem';
string = 'Hello World!';

public_key =
   OpenSSL::PKey::RSA.new(File.read(public_key_file))
encrypted_string =
   Base64.encode64(public_key.public_encrypt(string))

print encrypted_string, "\n"
</pre>
<p>Simply, <em>public_key_file</em> is path to the file containing the public key, and <em>string</em> is the string to encrypt.  We open the public key and then use <em>public_encrypt</em> to encrypt it.  Because the encrypted string is binary I have converted to text using <a href="http://en.wikipedia.org/wiki/Base64">Base64</a>.  If your are storing the encrypted string in a database that can hold binary data, you could change:</p>
<pre><code>encrypted_string = Base64.encode64(public_key.public_encrypt(string))</code></pre>
<p>to:</p>
<pre><code>encrypted_string = public_key.public_encrypt(string)</code></pre>
<p>Now that we have encrypted data, we&#8217;ll want to be able to get it back.</p>
<pre name="code" class="ruby">
#!/usr/bin/env ruby

require 'openssl'
require 'base64'

private_key_file = 'private.pem';
password = 'boost facile'

encrypted_string = %Q{
qBF3gjF8iKhDh+g+TOvAzBkJA/1d2lD8RUyz2Ol+s1OpLB5aA3RA7EHm0KGL
XaP3upvJ7I5rN1yO9Qat9kyRQu9OMqAUmFvwUaiW/1NPjxnpmcFn9mhkttP9
qfO6iIfyxErUqKIxHYqavyPmivre9eEcXiBdtIK6NJJKG3WmSfIFgpZ6eBWI
wxlZg+x0fI4L2JsODMGx5Khn7CUt0bTkH6HMHwxEG24NbsmrqtC2zn8Hm/87
UyN5ZCDyJ/mtIHAjzPry6vbVPTF0QCR4lZ7uSt/W7JZ0tNgX7eQQwoPCgbqU
/uwRCwww/c407jw7YEE5Lgpx20/jyLXJwvZHxNEcxA==
}

private_key =
  OpenSSL::PKey::RSA.new(File.read(private_key_file),password)

string =
  private_key.private_decrypt(Base64.decode64(encrypted_string))

print string, "\n"
</pre>
<p>Here <em>private_key_file</em> is path to the file containing the private key, <em>password</em> and <em>encrypted_string</em> is the string to decrypt.  In a real application you would not want to hard-code the password, rather you should prompt for it in some way.</p>
<p>Again we are using Base64 to make the encrypted string human readable.  If this is not necessary, change:</p>
<pre><code>string = private_key.private_decrypt(Base64.decode64(encrypted_string))</code></pre>
<p>to:</p>
<pre><code>string = private_key.private_decrypt(encrypted_string)</code></pre>
<p>As noted above, you can not use this method to encrypt anything larger than the key size minus 11 bytes of overhead (<a href="http://en.wikipedia.org/wiki/Padding_%28cryptography%29">padding</a>).  In this case we have a 2048 bit key which gives 256 &#8211; 11 = 245 bytes.   The temptation is to increase the key size to accommodate more data, but this quickly become to slow to be useful.  The correct way to accomplish this is to use public key encryption to encrypt random password, which, in turn is used to encrypt the data using <a href="http://en.wikipedia.org/wiki/Symmetric_cryptography">symmetric-key encryption</a>.   I&#8217;ll cover this next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://stuff-things.net/2007/06/11/encrypting-sensitive-data-with-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>
