Project-3 / RISC-V Cypher / caesarencrypt.s
caesarencrypt.s
Raw
.include "common.s"
.text
# -----------------------------------------------------------------------------
# caesarEncrypt: This function encrypts a string using a Caesar Cipher with both uppercase and lowercase keys.
#
# Args:
# 	a0: pointer to a string to encrypt
# 	a1: uppercase key, represented by a positive integer value
#	a2: lowercase key, represented by a positive integer value
# Returns:
#	a0: pointer to the encrypted string
#
# Register Usage:
# Explain your register usage here
# -----------------------------------------------------------------------------
caesarEncrypt:

    mv t0, a0  # we will load a0 to a temp register
    
    li t5, 26  # We are storing the number which we will % with in a temp register    
#------------------------------------------------------------------------------
caesarEncryptLoop:
    
    lbu t1, 0(t0)  #loading character from the string

   
    beqz t1, printEncryptedString  # checks for end of string and then jumps to print 

    # Check if the current character is an uppercase letter
    li t2, 'A'  # loading ascii values of A
    li t3, 'Z'  # Loading ascii values of Z
    blt t1, t2, lowercaseEncrypt     # checks if ascii smaller than A
    bgt t1, t3, lowercaseEncrypt     # checks if ascii is bigger than Z

    # Map the uppercase letter to a number 
    li t4, 'A'  
    sub t1, t1, t4

    # adding key and modulus with 26
    add t1, t1, a1
    remu t1, t1, t5

    # Map the number back to an uppercase letter
    add t1, t1, t4

    j continueEncryptLoop
#------------------------------------------------------------------------------
lowercaseEncrypt:
    #follows the same steps as uppercase 
    li t2, 'a'  # loading ascii values of a
    li t3, 'z'  # loading ascii values of z
    blt t1, t2, continueEncryptLoop # checks if ascii smaller than a
    bgt t1, t3, continueEncryptLoop # checks if ascii smaller than z

    # Map the lowercase letter to a number 
    li t4, 'a'  
    sub t1, t1, t4

    # adding key and modulus with 26
    add t1, t1, a2
    remu t1, t1, t5

    # Map the number back to an lowercase letter
    add t1, t1, t4
#------------------------------------------------------------------------------
continueEncryptLoop:
    # Store the encrypted character back 
    sb t1, 0(t0)

    # Print the encrypted character
    mv a0, t1
    li a7, 11  
    ecall

    # Move to the next character in the string
    addi t0, t0, 1

    j caesarEncryptLoop
#------------------------------------------------------------------------------
printEncryptedString:
    # Return the pointer to the encrypted string in a0
    mv a0, t0

    ret
#------------------------------------------------------------------------------