diff --git a/svr-authpubkey.c b/svr-authpubkey.c
index 6612194886d274f27092f4e0595f9213c259fe38..04d1b139cb21da2757a84e4f2c57985089ace755 100644
--- a/svr-authpubkey.c
+++ b/svr-authpubkey.c
@@ -200,6 +200,10 @@ static int checkpubkey_line(buffer* line, int line_num, char* filename,
 		return DROPBEAR_FAILURE; /* line is too short for it to be a valid key */
 	}
 
+	/* compare the algorithm. +3 so we have enough bytes to read a space and some base64 characters too. */
+	if (line->pos + algolen+3 > line->len) {
+		goto out;
+	}
 	/* check the key type */
 	if (strncmp((const char *) buf_getptr(line, algolen), algo, algolen) != 0) {
 		int is_comment = 0;