Go to most recent revision | Details | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
2 | daniel-mar | 1 | #!/usr/bin/php |
2 | <?php |
||
3 | |||
4 | // Generate keypair with: |
||
5 | // openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:8192 |
||
6 | // openssl rsa -pubout -in private.pem -out public.pem |
||
7 | |||
8 | if ($argc < 2) { |
||
9 | die("Syntax: $argv[0] file1 [file2 ...]\n"); |
||
10 | } |
||
11 | |||
12 | if (!file_exists(__DIR__.'/private.pem')) { |
||
13 | echo "Key private.pem not found\n"; |
||
14 | } |
||
15 | |||
16 | for ($i=1; $i<$argc; $i++) { |
||
17 | $file = $argv[$i]; |
||
18 | |||
19 | $cont = file_get_contents($file); |
||
20 | $original = $cont; |
||
21 | |||
22 | if (strpos($cont, '<?php') === false) { |
||
23 | echo "Not a PHP file: $file\n"; |
||
24 | continue; |
||
25 | } |
||
26 | |||
27 | $naked = preg_replace('@<\?php /\* <ViaThinkSoftSignature>(.+)</ViaThinkSoftSignature> \*/ \?>\n@ismU', '', $cont); |
||
28 | |||
29 | $hash = hash("sha256", $naked.basename($file)); |
||
30 | |||
31 | $pkeyid = @openssl_pkey_get_private('file://'.__DIR__.'/private.pem'); |
||
32 | openssl_sign($hash, $signature, $pkeyid, OPENSSL_ALGO_SHA256); |
||
33 | openssl_free_key($pkeyid); |
||
34 | |||
35 | if (!$signature) { |
||
36 | echo "ERROR: $file\n"; |
||
37 | continue; |
||
38 | } |
||
39 | |||
40 | $sign_line = '<?php /* <ViaThinkSoftSignature>'.base64_encode($signature).'</ViaThinkSoftSignature> */ ?>'; |
||
41 | if (substr($cont,0,2) === '#!') { |
||
42 | // Preserve shebang |
||
43 | $shebang_pos = strpos($naked, "\n"); |
||
44 | $shebang = substr($naked, 0, $shebang_pos); |
||
45 | $rest = substr($naked, $shebang_pos+1); |
||
46 | $cont = $shebang."\n".$sign_line."\n".$rest; |
||
47 | } else { |
||
48 | $cont = $sign_line."\n".$naked; |
||
49 | } |
||
50 | |||
51 | if ($cont != $original) { |
||
52 | echo "Signed: $file\n"; |
||
53 | file_put_contents($file, $cont); |
||
54 | } else { |
||
55 | echo "Already signed: $file\n"; |
||
56 | } |
||
57 | } |
||
58 |