[Haskell-cafe] Re: Crypto-API is stabilizing

Heinrich Apfelmus apfelmus at quantentunnel.de
Sat Sep 4 06:23:31 EDT 2010

Sebastian Fischer wrote:
> Thomas DuBuisson wrote:
>>>>  data Key = Key {
>>>>               encrypt   :: B.ByteString -> B.ByteString,
>>>>               decrypt   :: B.ByteString -> B.ByteString,
>>>>               keyLength :: BitLength,
>>>>               serialize :: B.ByteString}
>>>>  rsa :: RandomGen g => BitLength -> g -> ((Key,Key), g)
>> One reason against this is simply that all the other constructs
>> (block/stream cipher, hashes) are classes, it would be odd for there
>> to be a single exception.

Chances are that you can express them like this as well. :)

>> A better reason is the data structure has
>> no way to implement generateKeyPair.

That's a non-problem: each algorithm (RSA, DSA, ...) implements a
function with the same type as  generateKeyPair . Compare

    rsa :: RangomGen g => BitLength -> g -> ((Key,Key), g)


    ((k1 :: RSA, k2), g') = generateKeyPair g

You always have to write down the name of the algorithm ("RSA") when
using  generateKeyPair , so you may as well drop it entirely.

> Also, the type-class approach is extensible in that new operations (for 
> example for signing) can be added via subclasses. Later extending the 
> key type above requires nesting.

That's an argument in favor of type classes, indeed. However, if the
extension applies to *all* key types, i.e. if you could merge the
subclasses into the superclass, then you can add the new fields to the
Key  type. If the record fields are read-only, this will not break
backwards compatibility.

> In general, I like this approach, but what are
>    encrypt privateKey
> or
>    decrypt publicKey
> supposed to do? A type-class solution also does not *prevent*
> programmers to perform such non-sensical calls, but the data-type
> solution *forces* programmers to provide non-sensical encrypt and
> decrypt functions when creating the public and private keys.
> Would it be desirable to prohibit such calls using the type system?

Unless the implementor of a new encryption algorithm uses different 
types to distinguish between public and private key, the type class 
approach forces him to provide non-sensical  encrypt  and  decrypt 
functions, too.

Heinrich Apfelmus


More information about the Libraries mailing list