OneCompiler

Encryption and decryption. Asm

1675

section .data
message db 'Enter message: ', 0 ; Prompt for user input
encrypt_msg db 'Encrypted: ', 0
decrypt_msg db 'Decrypted: ', 0
key db 3 ; Shift amount for Caesar cipher

section .bss
input resb 128 ; Buffer for user input (128 bytes)
encrypted resb 128 ; Space for encrypted message
decrypted resb 128 ; Space for decrypted message

section .text
global _start ; Entry point for the program

_start:
; Print prompt for user input
mov rsi, message ; Message prompt
call print_string

; Read user input
mov rsi, input                  ; Buffer for input
call read_input

; Encrypt the message
mov rsi, input                  ; Source string address (input)
mov rdi, encrypted              ; Destination for encrypted string (output)
mov al, byte [key]              ; Load key (shift amount)
call encrypt                    ; Call encrypt function

; Print encrypted message
mov rsi, encrypt_msg            ; Message prefix
call print_string
mov rsi, encrypted              ; Encrypted message
call print_string

; Decrypt the message
mov rsi, encrypted              ; Source string address (input)
mov rdi, decrypted              ; Destination for decrypted string (output)
neg al                          ; Negate shift amount for decryption
call encrypt                    ; Call encrypt function

; Print decrypted message
mov rsi, decrypt_msg            ; Message prefix
call print_string
mov rsi, decrypted              ; Decrypted message
call print_string

; Exit program
mov eax, 60                     ; Syscall number for exit
xor edi, edi                    ; Exit status 0
syscall                         ; Make the syscall

encrypt:
mov rcx, 128 ; Set counter to 128 (max buffer size)

encrypt_loop:
lodsb ; Load byte from [rsi] into al
test al, al ; Test if al is 0 (null terminator)
jz done ; If zero (end of string), jump to done
add al, bl ; Add the key value to al (shift character)
stosb ; Store byte from al to [rdi]
loop encrypt_loop ; Repeat loop for all characters

done:
ret ; Return from function

print_string:
mov rdx, 128 ; Number of bytes to write (max buffer size)
mov rax, 1 ; Syscall number for sys_write
mov rdi, 1 ; File descriptor 1 (stdout)
syscall ; Make the syscall
ret

read_input:
mov rdx, 128 ; Number of bytes to read (max buffer size)
mov rax, 0 ; Syscall number for sys_read
mov rdi, 0 ; File descriptor 0 (stdin)
syscall ; Make the syscall
ret