; R5: msg
; R6: modulus
; R7: exponent
; R0: msg**exponent [modulus]
RSAsignature:
    MOV     R1, #1
    BTL     R0, R6                  ;modulus bit length
    FP      R6, R0                  ;initialize modular coprocessor

    MOV     R6, #32
    MOV     R4, R6
    RND     R4                      ;random divisor
    SLL     R3, R1, R6
    SRL     R3, R3, R1
    OR      R4, R4, R3
    OR      R4, R4, R1              ;set msb and lsb of divisor
    MOV     R8, R4                  ;save mask
; R4 : divisor
; R6 : bit length of divisor
; R7 : dividend
binary_euclidean_division:
    BTL     R0, R7                  ;length of dividend
    SUB     R0, R0, R6
    ADD     R0, R0, R1
    SLL     R4, R4, R0
    XOR     R6, R6, R6
    JR      startBinary_euclidean_division
binary_euclidean_divisionLoop:
    SLL     R6, R6, R1
    SRL     R4, R4, R1
    SUB     R3, R7, R4
    JNCR    startBinary_euclidean_division
    ADD     R6, R6, R1              ;update quotient
    MOV     R7, R3                  ;update remainder
startBinary_euclidean_division:
    SUB     R0, R0, R1
    JCR     binary_euclidean_divisionLoop

    MOVRR   R0                      ;get R**2 mod modulus in R0
    MM      R5, R5, R0              ;put msg in Montgomery form
    CR      exponentiation
    MOV     R9, R0                  ;save msg**remainder
    MOV     R7, R8
    CR      exponentiation
    MOV     R5, R0                  ;msg**mask is the new message
    MOV     R7, R6
    CR      exponentiation
    MOV     R4, R9
    MM      R0, R0, R4              ;msg**(quotient*mask)*msg**remainder
    MM1     R0, R0
    STP

exponentiation:
    MOVRR   R0
    MM1     R0, R0                  ;initialize result with R
    BTL     R4, R7                  ;initialize i, to read bit i of exponent
    MOV     R3, R1
    JR      startExponentiation
exponentiationLoop:
    SRL     R2, R7, R4              ;shift exponent of i bits
    AND     R2, R2, R1              ;get lsb
    ADD     R2, R2, R2              ;===
    XOR     R2, R2, R3              ;with two lookup tables,
    MOV     R3, =tabAtomic          ;select next operation (in R2)
    ADD     R3, R3, R2              ;(either square or mult)
    MOVCW   R3                      ;and how to update counter i (in R3)
    MOV     R2, =tabOperation       ;(decrement 'i' or not)
    ADD     R2, R2, R3              ;
    MOVCW   R2                      ;
    AND     R3, R3, R1              ;===
    JA      R2
startExponentiation:
    SUB     R4, R4, R3
    JCR     exponentiationLoop
    RET
tabAtomic:
    .word   1, 1, 3, 0
tabOperation:
    .word   =square, =square, 0, =mult

square:
    MM      R0, R0, R0
    JR      startExponentiation
mult:
    MM      R0, R0, R5
    JR      startExponentiation

