Skip to content

crypto.rc4: new_cipher should return a reference to the Cipher for consistency with other ciphers#24113

Merged
spytheman merged 1 commit into
vlang:masterfrom
einar-hjortdal:bugf_rc4-cipher-return-type
Apr 3, 2025
Merged

crypto.rc4: new_cipher should return a reference to the Cipher for consistency with other ciphers#24113
spytheman merged 1 commit into
vlang:masterfrom
einar-hjortdal:bugf_rc4-cipher-return-type

Conversation

@einar-hjortdal

@einar-hjortdal einar-hjortdal commented Apr 2, 2025

Copy link
Copy Markdown
Contributor

if x.crypto.chacha20 new_cipher returns !&Cipher, then all new_cipher functions that return a cipher.Stream implementation should return a reference for consistency.

From here

struct WireChannel {
mut:
	conn          &net.TcpConn
	reader        &io.BufferedReader
	writer        &io.BufferedWriter
	plugin        string
	crypto_reader &cipher.Stream
	crypto_writer &cipher.Stream
}

fn (mut c WireChannel) set_crypt_key(plugin string, session_key []u8, nonce []u8) ! {
	c.plugin = plugin
	match plugin {
		chacha20_64_plugin_name, chacha20_32_plugin_name {
			mut digest := sha256.new()
			digest.write(session_key)!
			key := digest.sum([]u8{})
			c.crypto_reader = chacha20.new_cipher(key, nonce)!
			c.crypto_writer = chacha20.new_cipher(key, nonce)!
		}
		rc4_plugin_name {
			// unlike assignment with chacha20.new_cipher, here the user needs 2 steps to assign a reference
			r := rc4.new_cipher(session_key)!
			w := rc4.new_cipher(session_key)!
			c.crypto_reader = &r
			c.crypto_writer = &w
		}
		else {
			return error(format_error_message('Unknown wire encryption plugin name: ${plugin}'))
		}
	}
}

With my proposed change, code looks cleaner and more consistent

fn (mut c WireChannel) set_crypt_key(plugin string, session_key []u8, nonce []u8) ! {
	c.plugin = plugin
	match plugin {
		chacha20_64_plugin_name, chacha20_32_plugin_name {
			mut digest := sha256.new()
			digest.write(session_key)!
			key := digest.sum([]u8{})
			c.crypto_reader = chacha20.new_cipher(key, nonce)!
			c.crypto_writer = chacha20.new_cipher(key, nonce)!
		}
		rc4_plugin_name {
			c.crypto_reader =  rc4.new_cipher(session_key)!
			c.crypto_writer =  rc4.new_cipher(session_key)!
		}
		else {
			return error(format_error_message('Unknown wire encryption plugin name: ${plugin}'))
		}
	}
}

@huly-for-github

Copy link
Copy Markdown

Connected to Huly®: V_0.6-22504

@spytheman spytheman merged commit 5c8fd15 into vlang:master Apr 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants