Archive for the ‘technical’ Category

Maze62: a dense and speedy alphanumeric encoding for binary data

May 16, 2011

Abstract

There is a need to encode binary data into a text format, such that it can be used without further encoding where only a subset of ASCII text is normally used: identifiers, URL parameters, HTTP form content, HTTP cookie values, and so on.

There is number of existing solutions to this problem, but I believe there is room for improvement to all of them, and I propose a new encoding which I dub “Maze62″.

Existing solutions

Base64

Every three bytes (24 bits) of the input get regrouped into four 6-bit numbers, and each such number gets represented with one of the 62 alphanumerics and two other characters. Read more: http://en.wikipedia.org/wiki/Base64

Base16 (BinHex)

Each byte of the input is split into two 4-bit numbers, and each such numbers gets represented by one of the alphanuerics, typically constrained to the set of the hex digits [0-9a-f].

Base32

Every five bytes (40 bits) of input get split into a  group of eight 5-bit numbers, and each such number is encoded with an alphnumeric.

Base10

The input byte array gets represented as a a very large integer number, which is printed in decimal notation.

Base62

The input byte array gets represented as a a very large integer number, which is then converted to base-62 representation, similar to Base10 just with a different base. Entire set alphanumerics is used to represent the “digits”.

Shortcomings of existing solutions

While base64 is the usual choice, there are often problems with the two non-alphanumeric characters. What’s worse, when encoding algorithm is chosen, it is not known which symbols will pose problems in any of the future places where the data is to be used. For example, a forward slash is difficult to use in a URL, and a dash is illegal as a first character in a DNS name. Ideally, this mess would be excluded from consideration, which can only be achieved by sticking to the 62 alphanumerics.

An ideal solution therefore is one that only uses alphanumerics, is as dense as possible, and allows for speedy processing. None of the aforementioned solutions satisfy that criteria. In particular:

Base64 is dense with only 33% explosion in size, but is using more than the 62 alphanumerics and thus is prone to mangling.

Base16 is easy to code, but 100% explosion in size make it undesirable.

Base32 is still a 60% explosion. Absent any better ideas this would be my weapon of choice.

Base62 is almost as dense as Base64, and is neatly contained in its character set, but unlike other discussed solutions the cost of encoding is quadratic to the size of the input, which is clearly unacceptable.

Proposed solution

If you would like to try to solve the problem yourself, read no further. Otherwise, the algorithm below defines Maze62 encoding and presents it for your attention:

The algorithm

  1. The input data is represented as a stream of bits.
  2. Six bits are read from the input stream into current value CV. CV is therefore 63 or less.
  3. CV is divided by 62, and the remainder of the division, a value that is certain to be less than 62, is represented with alphanumeric and is written into the output stream of characters
  4. In theory, we must also store the quotient, which is either one or zero. However there is an important fact to be noted  – whenever the remainder of the division by 62 is larger than one, the quotient cannot be anything but zero. Given that the remainder is already emitted into the output stream, emitting the quotient would result into no new information being added, unless said remainder is either zero or one. Only in the latter case we also need to preserve and emit the quotient, which is also limited to single bit of data.
  5. Therefore, if the remainder is more than one, go to step 2
  6. If remainder is zero or one, memorize the one bit which represents the quotient
  7. Read five bits from the input stream into CV.
  8. Shift CV by one bit to the left, and insert the quotient from step 6 as the least significant bit.
  9. Go to step 3

The algorithm terminates after no more data can be read from the input and last piece of data is written out, including the potential stray quotient.

Analysis

The proposed encoding algorithm is linear in speed, nearly as dense as Base64, and fully constrained to alphanumeric set of characters. The only downside is a somewhat tricky implementation, but it’s not much worse than Base64. As I refine my python implementation of the algorithm I will post results on the comparative encoding efficiency.

The name

The name of the encoding is an amalgamation of “base62″ and the word amazing, hence “maze62″.

What’s next.

I will be publishing the python source code I have written to test this idea in the coming days. If there is interest, we could organize a public repository of Maze62 implementations in other languages, as well as a set of acceptance tests for independent implementations.

Discussion

In addition to the comments below there’s a discussion going on on hacker news: http://news.ycombinator.com/item?id=2553753

Further reading

In particular the reference to base85 encoding may prove useful: http://en.wikipedia.org/wiki/Base85

Making sense of Amazon EC2 reserved instance savings.

November 3, 2010

Amazon EC2 allows you to prepay a reservation fee in exchange for much lower hourly instance rates. Savings abound.

However, there’s a little problem – if you decide to upgrade to a beefier instance, change the availability zone, or leave AWS altogether, the fee is non-refundable, and you can’t resell your reservation to someone else. So should you pre-pay or not?

I have a simple answer for you: if you’re likely to be using your Linux box for about 8.5 months or more, you should prepay for 3 years, because that’s how many months it takes for the cost of the reservation to amortize through the lower hourly rates. The same threshold for a Windows box is about 7 months.

The whole breakdown can be found in this Google Spreadsheet, which also has other data such as TCO and the 1-year reservation math.

I found that “months-to-breakeven” is a number that’s much easier to grasp than the accurate but rather dry pricing data on Amazon’s pricing page. Hopefully Amazon will add it there, or at least provide their prices as a public dataset so that I don’t need to copy-paste the relevant data together.

(technical) A practical way of encrypting backups

September 27, 2010

TL/DR.

Openssl (a payment-free, GUI-free, setup-free tool) can be used to perform asymmetric encryption on large files without hassle. Rather unexpectedly, one needs to use the SMIME command with DEM encoding to achieve the desired result.

Problem.

A sysadmin wants to perform his duty[1] to encrypt the off-site backups in his care, and he wishes for a solution which is reliable and easy to use. In particular:

  1. Resilient against hackers.
  2. Resilient against accidental leaks and human errors, even if leaks are partial. People make mistakes.
  3. Resilient against key loss, which equates data loss and obviously defeats the purpose of doing the backup.
  4. No messy software to install on the server. Ideally, that would be just an extra line in the backup script and maybe a binary which can be simply copied during deployment.
  5. No configuration hassles on per-server basis. Obviously, no GUIs to click through for each machine. Ideally, no configuration at all, so scripts can be simply copied directly form the source control to a bare machine.
  6. It shouldn’t cost and an arm and a leg.
  7. The data formats should not become obsolete and unsupported.

The most simple, obvious, and wrong solution.

Symmetric encryption is easy to use – the user comes up with the “symmetric key”, generally a text pass-phrase[2], and that key is then used to both encrypt the data during backups and decrypt it during restore. Popular free tools as 7-Zip or Openssl make it easy to encrypt backups, and then to decrypt them back (optionally compressing them as well):

7za a myfile.7z myfile.bkp -pPassPhrase
7za e myfile.7z -pPassPhrase

openssl enc -aes-256-cbc -salt -in myfile.bkp -out myfile.bkp.enc -pass pass:PassPhrase
openssl enc -d -aes-256-cbc -in myfile.bkp.enc -out myfile.bkp.unenc -pass pass:PassPhrase

And yet it’s the wrong approach. The problem with symmetric encryption is in its very definition – the same key that is used to encrypt can be used to decrypt.

  • If the key is stored in the source of the script, a source code leak will automatically compromise all backups taken previously.
  • If the key is not stored in the source of the script it has to be provisioned when the server is being setup, hence no simple copy-deployment is possible. Either a manual intervention is required or a separate key-management procedure must be set up and followed diligently.
  • If a machine that is doing periodic backups of itself is compromised, not only that machine’s current data set is compromised, which is generally inevitable[3], but many other backups are compromised too – past backups of the data assumed to be long gone made on the same machine, and all backups made on other machines with the same key.
  • To partially mitigate the previous problem different keys could be used for different servers and during different time periods, but that will lead to explosion in the number of keys which need to be remembered and correctly applied in order to restore the backups. A key-management database will become inevitable at this point.

The right solution.

Asymmetric encryption is a much better alternative for the backup encryption problem – the encryption key is split in two parts, and one part can only be used to encrypt the data, while the other can also decrypt it. The latter is called “private key”, while the former is known as “public key” – there is no risk in exposing it, and so one doesn’t need to worry about any of the problems mentioned in the previous chapter. One would normally be restoring the backups several orders of magnitude less frequently than creating them, and so separating keys needed to encrypt and decrypt the data offers substantial improvement in security and manageability.

The easiest way this author found to implement such solution in practice is to use a free and open-source tool called Openssl. Many systems already have it installed, and if not, the binary can be copied without any installation. [4]

The first step is to generate the private and public keys [5]. This only needs to be done once.

openssl req -x509 -nodes -days 100000 -newkey rsa:2048 -keyout MyCompanyBackupsPRIVATE.pem -out MyCompanyBackupsPublicCert.pem -subj ‘/’

The private key is placed into the file MyCompanyBackupsPRIVATE.pem, and the public key is in MyCompanyBackupsPublicCert.pem. The two keys can now be used to encrypt the valuable data:

openssl smime -encrypt -aes256 -in ImportantFile.bkp -binary -outform DEM -out ImportantFile.bkp.openssl_smime_dem MyCompanyBackupsPublicCert.pem

and to decrypt it:

openssl smime -decrypt -in ImportantFile.bkp.openssl_smime_dem -binary -inform DEM -inkey MyCompanyBackupsPRIVATE.pem -out ImportantFile.bkp.decrypted

That is all there is to know – the three simple commands, and the fact that the private key should be stored in a safe place until a backup needs to be restored.

Closing remarks.

A script implementing such scheme would do well to link back to this page for the benefit of the subsequent mantinainers.

It is possible to specify more than one private key in the encryption command and thus encrypt the data with several keys using very little extra space. This would be practical if one key is used for regular every day operations and is replaced regularly, while another “failsafe” key is kept by the company executives in case of emergency and is never changed.

Downloading: http://www.google.com/search?q=openssl+download

Coming up next: the simplest script to take a set of files, compress them, slice, encrypt, and upload to Amazon S3 for safekeeping.

Footnotes.

[1] Why encrypt? Data is like DNA – once it spills, the residue is nearly impossible to erase, and so it’s best to keep both neatly contained in the first place. “Secure erase” becomes a fiction when remapped sectors, untrained interns, drifting organizational responsibilities, and cost-efficient third-party cloud storage providers enter the picture. Maintaining privacy of a comparatively small set of keys is a lot easier than doing the same for a large set of backup data.

[2] Actual encryption is performed using a binary key, but most tools provide a way to generated one from an easy to remember text string, a “pass-phrase”, so for this discussion we can assume the two to be equivalent. It needs to be noted however, that there is more than one way to translate a text pass-phrase into a binary key, so it is important to use the same tool to decrypt the data that was used to encrypt it.

[3] Leaving aside the TPM-based solutions, which don’t seem to have gained much traction.

[4] Unlike, say, GPG which requires installation and a somewhat involved key import/export procedure.

[5] Technically, this command is generating a private key and a certificate that has the public key inside of it. The distinction, however, is immaterial in this case. Strangely, SMIME command is the easiest way to get asymmetric encryption using Openssl, and it requires a certificate.


Follow

Get every new post delivered to your Inbox.