MessagesSignature.java

/* ========================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyright 2009-2024, Arnaud Roques
 *
 * Project Info:  https://plantuml.com
 * 
 * If you like this project or if you find it useful, you can support us at:
 * 
 * https://plantuml.com/patreon (only 1$ per month!)
 * https://plantuml.com/paypal
 * 
 * This file is part of PlantUML.
 *
 * PlantUML is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PlantUML distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 *
 * Original Author:  Arnaud Roques
 *
 */
package net.sourceforge.plantuml.error.messages;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

import net.sourceforge.plantuml.utils.SignatureUtils;

/**
 * Checks the signature of messages.yaml: its last line is
 * {@code # signature: <base64>}, an RSA signature (PKCS#1 v1.5, SHA-512, the
 * {@code SHA512withRSA} of Java) of everything before that line, with every line
 * break written {@code \n}. tools/messages-signature/SignMessages.java writes it.
 *
 * Only {@link BigInteger#modPow} and SHA-512 are needed here, not
 * {@code java.security.Signature}, to stay easy to run under TeaVM.
 */
final class MessagesSignature {

	static final String PREFIX = "# signature: ";

	// DER of the DigestInfo of SHA-512 (RFC 8017, 9.2), followed by the 64 bytes of the hash
	private static final byte[] SHA512_DIGEST_INFO = { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte) 0x86, 0x48,
			0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 };

	private MessagesSignature() {
	}

	/**
	 * The signed content (everything before the signature line, line breaks
	 * written {@code \n}) when the signature is valid for this public key, or null
	 * when it is missing or invalid.
	 */
	static String verify(byte[] data, BigInteger e, BigInteger n) {
		final String text = new String(data, StandardCharsets.UTF_8).replace("\r\n", "\n");

		// The signature line is the last one; line breaks after it are allowed
		int end = text.length();
		while (end > 0 && text.charAt(end - 1) == '\n')
			end--;

		final int lineStart = text.lastIndexOf('\n', end - 1) + 1;
		final String lastLine = text.substring(lineStart, end);
		if (lastLine.startsWith(PREFIX) == false)
			return null;

		final String content = text.substring(0, lineStart);
		final byte[] signature;
		try {
			signature = Base64.getDecoder().decode(lastLine.substring(PREFIX.length()).trim());
		} catch (IllegalArgumentException ex) {
			return null;
		}

		final byte[] expected = expectedBlock(content, n);
		if (expected == null || signature.length != expected.length)
			return null;

		final BigInteger s = new BigInteger(1, signature);
		if (s.compareTo(n) >= 0)
			return null;

		final byte[] actual = toFixedLength(s.modPow(e, n), expected.length);
		if (actual == null || MessageDigest.isEqual(expected, actual) == false)
			return null;

		return content;
	}

	/**
	 * The block that the signature of this content gives back with the public key:
	 * {@code 00 01 FF ... FF 00 DigestInfo SHA-512(content)}, as long as the modulus.
	 */
	static byte[] expectedBlock(String content, BigInteger n) {
		final byte[] hash;
		try {
			hash = SignatureUtils.getSHA512raw(content.getBytes(StandardCharsets.UTF_8));
		} catch (Exception ex) {
			return null;
		}
		final int length = (n.bitLength() + 7) / 8;
		final int padding = length - 3 - SHA512_DIGEST_INFO.length - hash.length;
		if (padding < 8)
			return null;

		final byte[] result = new byte[length];
		result[0] = 0x00;
		result[1] = 0x01;
		for (int i = 0; i < padding; i++)
			result[2 + i] = (byte) 0xFF;

		result[2 + padding] = 0x00;
		System.arraycopy(SHA512_DIGEST_INFO, 0, result, 3 + padding, SHA512_DIGEST_INFO.length);
		System.arraycopy(hash, 0, result, 3 + padding + SHA512_DIGEST_INFO.length, hash.length);
		return result;
	}

	// The unsigned big-endian bytes of the number, padded with zeros to the length
	private static byte[] toFixedLength(BigInteger number, int length) {
		final byte[] raw = number.toByteArray();
		int start = 0;
		while (start < raw.length - 1 && raw[start] == 0)
			start++;

		final int size = raw.length - start;
		if (size > length)
			return null;

		final byte[] result = new byte[length];
		System.arraycopy(raw, start, result, length - size, size);
		return result;
	}

}