Skip to content

Instantly share code, notes, and snippets.

@tarjeihsch
Created February 27, 2025 23:52
Show Gist options
  • Save tarjeihsch/6fe7e36675cf2ac5a7b4d78733a9af2c to your computer and use it in GitHub Desktop.
Save tarjeihsch/6fe7e36675cf2ac5a7b4d78733a9af2c to your computer and use it in GitHub Desktop.
XOR Cipher (NASM x86_64 Linux)
%define CHUNK_SIZE 4096
%define KEY_SIZE 64
%define PATH_SIZE 256
section .bss
input_buffer resb CHUNK_SIZE
output_buffer resb CHUNK_SIZE
argument_key resb KEY_SIZE
argument_path resb PATH_SIZE
file_handle resq 1
bytes_read resq 1
section .text
global _start
_start:
; Write all bytes in buffer to 0
mov rdi, argument_key
xor rax, rax
mov rcx, KEY_SIZE
rep stosb
; Write all bytes in buffer to 0
mov rdi, argument_path
xor rax, rax
mov rcx, PATH_SIZE
rep stosb
; Load argument 1 (Argv[1] = 8 * 2)
mov rsi, [rsp + 16]
mov rdi, argument_key
mov rcx, KEY_SIZE
rep movsb
; Load argument 2 (Argv[2] = 8 * 3)
mov rsi, [rsp + 24]
mov rdi, argument_path
mov rcx, PATH_SIZE
rep movsb
; Load file
mov rax, 2
mov rdi, argument_path
mov rsi, 0x002 ; O_RDWR
mov rdx, 0666 ; rw-rw-rw-
syscall
; Exit on failure
cmp rax, 0
jl exit
; Store file handle
mov [file_handle], rax
; Attempt to read a chunk of bytes into the input buffer
.xor_read:
; Read chunk into input buffer
mov rax, 0
mov rdi, [file_handle]
mov rsi, input_buffer
mov rdx, CHUNK_SIZE
syscall
cmp rax, 0
je stop
jl stop
; Store file size
mov [bytes_read], rax
mov rcx, rax
mov rbx, rax
; Perform XOR cipher operation on each byte (Output = Input XOR Key)
.xor_translate:
mov dl, [input_buffer + rcx - 1]
mov r8, rcx
and r8, KEY_SIZE - 1
xor dl, [argument_key + r8]
mov [output_buffer + rcx - 1], dl
loop .xor_translate
; Write the modified bytes back to the file at it's respective file offset
.xor_write:
; Move file pointer
mov rax, 8
mov rdi, [file_handle]
mov rsi, rbx
neg rsi
mov rdx, 1
syscall
cmp rax, 0
jl stop
; Write output buffer to file
mov rax, 1
mov rdi, [file_handle]
mov rsi, output_buffer
mov rdx, rbx
syscall
cmp rax, rbx
jl stop
; Prepare a new chunk of bytes and repeat the process
jmp .xor_read
stop:
; Dispose file handle
mov rax, 3
mov rdi, [file_handle]
syscall
exit:
; Exit application
mov rax, 60
xor rdi, rdi
syscall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment