#!/bin/perl

# -----------------------------------------------------------------------
# Project: zorro
# File: sign.pl
# Copyright (C) 2015 Nintendo, All rights reserved.
# These coded instructions, statements, and computer programs contain proprietary
# information of Nintendo and/or its licensed developers and are protected by
# national and international copyright laws. They may not be disclosed to third
# parties or copied or duplicated in any form, in whole or in part, without the
# prior written consent of Nintendo.
# The content herein is highly confidential and should be handled accordingly.
# -----------------------------------------------------------------------

# Dependencies
# ============
# The dependencies of this file are detailled in the comments at the beginning of the sign.pl script
# file.

# Usage example
# =============
# Assume you have your 768 bit RSA public key in DER format in pubKey.der, and signature_file a file
# containing the signature generated by sign.pl or zorro library (with public data to contents of
# pubKey.der), with 8 bytes overhead.
# Call the tool:
# ./verify.pl signature_file pubKey.der 8 > message

use strict;
use warnings;

use Crypt::Cipher::AES;
use Crypt::PK::RSA;
use Crypt::Digest::SHA1 qw(sha1);

if ($#ARGV != 2) {
	print "Usage: ./verify.pl message_file pubKey.der overhead\n";
	exit;
}

my $signature=$ARGV[0];
my $pubkeyFile=$ARGV[1];
my $overhead=$ARGV[2];

if ($overhead >= 20)
{
    die "Too much overhead for SHA1";
}

my $pubKey = Crypt::PK::RSA->new($pubkeyFile);
my $modulusSize = $pubKey->size;

my $signatureSize = -s $signature;
my $signatureContents;

my $pubkeyFileSize = -s $pubkeyFile;
my $pubkeyContents;


open(MSG, $signature) or die "Could not open $signature";
binmode MSG;
read MSG, $signatureContents, $signatureSize;
close(MSG);
if ($signatureSize != length($signatureContents))
{
    die "Signature size different from expected";
}

open(PKEY, $pubkeyFile) or die "Could not open $pubkeyFile";
binmode PKEY;
read PKEY, $pubkeyContents, $pubkeyFileSize;
close(PKEY);
if ($pubkeyFileSize != length($pubkeyContents))
{
    die "Public key size different from expected";
}

if ($signatureSize < $modulusSize)
{
    die "Signature too short";
}

my $clearPart = substr $signatureContents, 0, -$modulusSize;
my $signPart = substr $signatureContents, -$modulusSize;

my $aesKey = sha1($pubkeyContents, $clearPart);
$aesKey = substr $aesKey, 0, 16;

my $aes = Crypt::Cipher::AES->new($aesKey);

my $scrambled0 = $pubKey->encrypt($signPart, 'none');

my $scrambled0FirstByte = substr $scrambled0, 0, 1;
my $scrambled0Next = substr $scrambled0, 1;
if (($scrambled0FirstByte & chr(0x80)) ne chr(0))
{
    die "Invalid signature";
}

my $scrambled1 = ($scrambled0FirstByte | chr(0x80)) . $scrambled0Next;

sub cmc_decrypt {
    my $aes = $_[0];
    my $message = $_[1];
    my $iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";

    my $interm = "";
    my $blockCount = length($message) / 16;
    for (my $i = $blockCount - 1; $i >= 0; --$i)
    {
        my $curSrc = substr $message, $i * 16, 16;
        $curSrc ^= $iv;
        $iv = $aes->decrypt($curSrc);
        $interm = $iv . $interm;
    }

    my $xoredBlock = substr $interm, 0, 16;
    my $lastBlock = substr $interm, -16;

    $xoredBlock ^= $lastBlock;

    my $bitstring = unpack "B*", $xoredBlock;
    my $bitshifted = substr $bitstring, 1;
    $bitshifted = $bitshifted . "0";

    my $need87 = substr $bitstring, 0, 1 == '1';

    my $mask = pack "B*", $bitshifted;

    if ($need87) {
        my $lastBlock = substr $mask, -1;
        my $beginning = substr $mask, 0, -1;
        my $xored = $lastBlock ^ chr(0x87);
        $mask = $beginning . $xored;
    }

    $iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    my $result = "";
    for (my $i = 0; $i < $blockCount; ++$i) {
        my $nextIv = substr $interm, 16 * $i, 16;
        $nextIv ^= $mask;
        my $cur = $aes->decrypt($nextIv);
        $result .= ($cur ^ $iv);
        $iv = $nextIv;
    }
    return $result;
}

my @descrambled;
$descrambled[0] = &cmc_decrypt($aes, $scrambled0);
$descrambled[1] = &cmc_decrypt($aes, $scrambled1);

my $result;

binmode(STDOUT) or die "cannot binmode standard output";

for(my $i = 0; $i < 2; $i++)
{
    my $descrambledWithoutDigest = substr $descrambled[$i], 0, -$overhead;
    my $digestToMatch = substr $descrambled[$i], -$overhead;

    $result = $clearPart;
    $result .= $descrambledWithoutDigest;

    my $digest = sha1($result);
    $digest = substr $digest, 0, $overhead;
    if ($digestToMatch eq $digest)
    {
        print STDOUT $result;
        exit 0;
    }
}


die "Invalid signature"
