001// SPDX-FileCopyrightText: 2018 Paul Schaub <vanitasvitae@fsfe.org> 002// 003// SPDX-License-Identifier: Apache-2.0 004 005package org.pgpainless.algorithm; 006 007import java.util.HashMap; 008import java.util.Map; 009 010import org.bouncycastle.bcpg.HashAlgorithmTags; 011 012/** 013 * An enumeration of different hashing algorithms. 014 * 015 * @see <a href="https://tools.ietf.org/html/rfc4880#section-9.4">RFC4880: Hash Algorithms</a> 016 */ 017public enum HashAlgorithm { 018 @Deprecated 019 MD5 (HashAlgorithmTags.MD5, "MD5"), 020 SHA1 (HashAlgorithmTags.SHA1, "SHA1"), 021 RIPEMD160 (HashAlgorithmTags.RIPEMD160, "RIPEMD160"), 022 SHA256 (HashAlgorithmTags.SHA256, "SHA256"), 023 SHA384 (HashAlgorithmTags.SHA384, "SHA384"), 024 SHA512 (HashAlgorithmTags.SHA512, "SHA512"), 025 SHA224 (HashAlgorithmTags.SHA224, "SHA224"), 026 ; 027 028 private static final Map<Integer, HashAlgorithm> ID_MAP = new HashMap<>(); 029 private static final Map<String, HashAlgorithm> NAME_MAP = new HashMap<>(); 030 031 static { 032 for (HashAlgorithm h : HashAlgorithm.values()) { 033 ID_MAP.put(h.algorithmId, h); 034 NAME_MAP.put(h.name, h); 035 } 036 } 037 038 /** 039 * Return the {@link HashAlgorithm} value that corresponds to the provided algorithm id. 040 * If an invalid algorithm id was provided, null is returned. 041 * 042 * @param id numeric id 043 * @return enum value 044 */ 045 public static HashAlgorithm fromId(int id) { 046 return ID_MAP.get(id); 047 } 048 049 /** 050 * Return the {@link HashAlgorithm} value that corresponds to the provided name. 051 * If an invalid algorithm name was provided, null is returned. 052 * 053 * @see <a href="https://datatracker.ietf.org/doc/html/rfc4880#section-9.4">RFC4880: ยง9.4 Hash Algorithms</a> 054 * for a list of algorithms and names. 055 * 056 * @param name text name 057 * @return enum value 058 */ 059 public static HashAlgorithm fromName(String name) { 060 return NAME_MAP.get(name); 061 } 062 063 private final int algorithmId; 064 private final String name; 065 066 HashAlgorithm(int id, String name) { 067 this.algorithmId = id; 068 this.name = name; 069 } 070 071 /** 072 * Return the numeric algorithm id of the hash algorithm. 073 * 074 * @return numeric id 075 */ 076 public int getAlgorithmId() { 077 return algorithmId; 078 } 079 080 /** 081 * Return the text name of the hash algorithm. 082 * 083 * @return text name 084 */ 085 public String getAlgorithmName() { 086 return name; 087 } 088}