- live browsing of Self object memory -

lobby traitscryptomachine

An abstract encryption/decryption machine.
     A distinction is made between plain text blocks (unencrypted) and
     cipher text blocks (encrypted). Both kinds of text blocks are
     represented as strings of fixed length, but the two kinds of
     text blocks need not have identical lengths.

CopyDowns: vector

CreatorPath: traits cryptomachine

Module: crypto

parent* = traits clonable
decrypt: =
( | len <- 47. plain <- ''. space <- 0 |
    "Return decryption of cipher."

    (cipher size %+ cipherBlockSize) != 0 ifTrue: [ 
        error: 'This text was encrypted using another block size.'.
    ].
    0 to: cipher size - cipherBlockSize By: cipherBlockSize Do: [|:i|
        plain: plain &
            (blockDecrypt: (cipher copyFrom: i UpTo: i + cipherBlockSize)).
    ].
    plain: plain & ''.   "Make sure that 'flatString' works."
    plain: plain flatString.
    [' ' != (plain at: space 
             IfAbsent: [error: 'rsa decrypt failed'])] whileTrue: [
        space: 1 + space.
    ].
    "Now we have plain text again, so let's get rid of all the filling/
     length info we added before encrypting."
    len: (plain copyFrom: 0 UpTo: space) asInteger.
    plain copyFrom: space + 1 UpTo: space + 1 + len)
encrypt: =
( | cipher <- ''. plain <- '' |
    "Return encryption of text."

    plain: text size printString, ' ', text.   "Include size."

    "Now fill up to integral multiple of block size."
    0 != (plain size %+ plainBlockSize) ifTrue: [|pad|
        pad: plainBlockSize - (plain size %+ plainBlockSize).
        plain: plain, (rand string: pad).
    ].
    0 to: plain size - plainBlockSize By: plainBlockSize Do: [|:i|
        cipher: cipher &
              (blockEncrypt: (plain copyFrom: i UpTo: i + plainBlockSize)).
    ].
    cipher flatString)
randomGenerator =
( 
    "Return random number generator (for setting seed etc.)."
    ^ rand)
randomGenerator: =
( 
    "Use r as random number generator in the future."
    rand: r.
    ^ self)
cshift = ( 2 power: typeSizes bitsPerByte)
descendantResponsibilities = traits cryptomachine descendantResponsibilities
int2text:Len: =
( | cs <- 47. t <- ''. x <- 47 |
    "Here we need to feed the length in, since the integer could have
     'leading zeros'."
    t: ('' copySize: l).
    x: m.
    cs: cshift.
    l - 1 downTo: 0 Do: [|:i| 
        t at: i PutByte: (x %+ cs) asSmallInteger.  
        x: x / cs. 
    ].
    0 != x ifTrue: [error: 'not all of integer used in int2text'].
    ^ t)
text2int: =
( | cs <- 47. m <- 0 |
    cs: cshift.
    textBlock  do: [ | :c | m: (m * cs) + c asByte. ].
    ^ m)