|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tests\Unit\Util\Crypto; |
| 4 | + |
| 5 | +use PHPUnit\Framework\TestCase; |
| 6 | + |
| 7 | +use Casper\Util\Crypto\Secp256K1Key; |
| 8 | + |
| 9 | +class Secp256K1KeyTest extends TestCase |
| 10 | +{ |
| 11 | + /** |
| 12 | + * @throws \Exception |
| 13 | + */ |
| 14 | + public function testCreateNewSecp256K1FromFile(): void |
| 15 | + { |
| 16 | + $compressedPublicKeyValue = '02c6d103561f83a41281d278e07e45905529bf25d74fa184631a309afe7bc3dc06'; |
| 17 | + $secp256k1KeyPair = Secp256K1Key::createFromPrivateKeyFile('tests/Assets/Secp256K1SecretKey.pem'); |
| 18 | + |
| 19 | + $this->assertEquals($compressedPublicKeyValue, $secp256k1KeyPair->getPublicKey()); |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * @throws \Exception |
| 24 | + */ |
| 25 | + public function testCantCreateNewSecp256K1FromWrongFile(): void |
| 26 | + { |
| 27 | + $this->expectException(\RuntimeException::class); |
| 28 | + $this->expectExceptionMessage('Invalid data.'); |
| 29 | + Secp256K1Key::createFromPrivateKeyFile('tests/Assets/Ed25519SecretKey.pem'); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @throws \Exception |
| 34 | + */ |
| 35 | + public function testExportPublicKeyInPem(): void |
| 36 | + { |
| 37 | + $publicKeyInPem = file_get_contents('tests/Assets/Secp256K1PublicKey.pem'); |
| 38 | + $secp256k1KeyPair = Secp256K1Key::createFromPrivateKeyFile('tests/Assets/Secp256K1SecretKey.pem'); |
| 39 | + |
| 40 | + $this->assertEquals($publicKeyInPem, $secp256k1KeyPair->exportPublicKeyInPem()); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * @throws \Exception |
| 45 | + */ |
| 46 | + public function testExportPrivateKeyInPem(): void |
| 47 | + { |
| 48 | + $privateKeyInPem = file_get_contents('tests/Assets/Secp256K1SecretKey.pem'); |
| 49 | + $secp256k1KeyPair = Secp256K1Key::createFromPrivateKeyFile('tests/Assets/Secp256K1SecretKey.pem'); |
| 50 | + |
| 51 | + $this->assertEquals($privateKeyInPem, $secp256k1KeyPair->exportPrivateKeyInPem()); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @throws \Exception |
| 56 | + */ |
| 57 | + public function testSigningAndVerification(): void |
| 58 | + { |
| 59 | + $message = 'Hello world'; |
| 60 | + $secp256k1KeyPair = Secp256K1Key::createFromPrivateKeyFile('tests/Assets/Secp256K1SecretKey.pem'); |
| 61 | + |
| 62 | + $signature = $secp256k1KeyPair->sign($message); |
| 63 | + $isVerified = $secp256k1KeyPair->verify($signature, $message); |
| 64 | + $this->assertTrue($isVerified); |
| 65 | + |
| 66 | + $corruptedSignature = str_replace('3', '2', $signature); |
| 67 | + $isVerified = $secp256k1KeyPair->verify($corruptedSignature, $message); |
| 68 | + $this->assertFalse($isVerified); |
| 69 | + } |
| 70 | +} |
0 commit comments