Subversion Repositories vnag

Rev

Rev 2 | Go to most recent revision | Details | Compare with Previous | 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
 
4 daniel-mar 40
	$sign_line = '<?php /* <ViaThinkSoftSignature>'."\n".split_equal_length(base64_encode($signature),65).'</ViaThinkSoftSignature> */ ?>';
41
 
42
	// We have to put the signature at the beginning, because we don't know if the end of the file lacks a PHP closing tag
2 daniel-mar 43
	if (substr($cont,0,2) === '#!') {
44
		// Preserve shebang
45
		$shebang_pos = strpos($naked, "\n");
46
		$shebang = substr($naked, 0, $shebang_pos);
47
		$rest = substr($naked, $shebang_pos+1);
48
		$cont = $shebang."\n".$sign_line."\n".$rest;
49
	} else {
50
		$cont = $sign_line."\n".$naked;
51
	}
52
 
53
	if ($cont != $original) {
54
		echo "Signed: $file\n";
55
		file_put_contents($file, $cont);
56
	} else {
57
		echo "Already signed: $file\n";
58
	}
59
}
60
 
4 daniel-mar 61
# ---
62
 
63
function split_equal_length($data, $width=65) {
64
	$out = '';
65
	for ($i=0; $i<strlen($data); $i+=$width) {
66
		$out .= substr($data, $i, $width)."\n";
67
	}
68
	return $out;
69
}
70