Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 3, 2025

Conversation

einar-hjortdal
Copy link
Contributor

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

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}'))
		}
	}
}

Copy link

Connected to Huly®: V_0.6-22504

@spytheman spytheman merged commit 5c8fd15 into vlang:master Apr 3, 2025
62 checks passed
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