Add Matricizer.choose_dimensions

Matrices can choose their dimensions based on hash algorithm

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2024-05-24 22:54:53 -07:00
parent 9298d72c17
commit 6aed63c069
2 changed files with 30 additions and 2 deletions

View File

@@ -163,7 +163,8 @@ def main() -> None:
case "randomart":
# 17x9 is what openssh uses
# TODO - allow configuring dimensions, maybe
matricizer = RandomartMatricizer(11, 6)
w, h = RandomartMatricizer.DIMENSIONS[args.hash]
matricizer = RandomartMatricizer(w, h)
case _:
assert False, f"invalid args.matrix: {args.matrix}"

View File

@@ -1,6 +1,6 @@
"All things that turn a hash into a matrix."
import abc
from typing import Mapping, Sequence
from typing import Mapping, Sequence, Self
from .palettes import Palette, DEFAULT_PALETTES, GRADIENT_PALETTES, MULTICOLOR_PALETTES
@@ -35,6 +35,16 @@ class Matricizer(metaclass=abc.ABCMeta):
:returns: the matrix converted from the hash data.
"""
@staticmethod
@abc.abstractmethod
def choose_dimensions(hash: str) -> tuple[int, int]:
"""
Choose the dimensions for this matrix based on the hash algorithm.
:param hash: the hash algorithm being used.
:returns: a width and height as a tuple.
"""
def choose_palette(
self, data: bytes, palettes: Mapping[str, Palette] | None = None
) -> Palette:
@@ -96,6 +106,10 @@ class NibbleMatricizer(Matricizer):
return cols
@staticmethod
def choose_dimensions(hash: str) -> tuple[int, int]:
return Self.DIMENSIONS[hash]
def choose_palette(
self, data: bytes, palettes: Mapping[str, Palette] | None = None
) -> Palette:
@@ -110,6 +124,15 @@ class RandomartMatricizer(Matricizer):
See: https://github.com/openssh/openssh-portable/blob/fc5dc092830de23767c6ef67baa18310a64ee533/sshkey.c#L1014
"""
DIMENSIONS = {
"md5": (7, 6),
"sha1": (7, 6),
"sha224": (8, 7),
"sha256": (8, 7),
"sha384": (11, 10),
"sha512": (11, 10),
}
def matricize(self, data: bytes) -> Matrix:
"""
Create a matrix based on the "randomart" algorithm from ssh-keygen.
@@ -148,6 +171,10 @@ class RandomartMatricizer(Matricizer):
rows[r][c] += 1
return rows
@staticmethod
def choose_dimensions(hash: str) -> tuple[int, int]:
return self.DIMENSIONS[hash]
def choose_palette(
self, data: bytes, palettes: Mapping[str, Palette] | None = None
) -> Palette: