]> git.mxchange.org Git - friendica.git/blob - include/certfns.php
helper functions for Diaspora cert mangling
[friendica.git] / include / certfns.php
1 <?php
2
3 require_once('library/ASNValue.class.php');
4
5 function DerToPem($Der, $Private=false)
6 {
7     //Encode:
8     $Der = base64_encode($Der);
9     //Split lines:
10     $lines = str_split($Der, 65);
11     $body = implode("\n", $lines);
12     //Get title:
13     $title = $Private? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
14     //Add wrapping:
15     $result = "-----BEGIN {$title}-----\n";
16     $result .= $body . "\n";
17     $result .= "-----END {$title}-----\n";
18  
19     return $result;
20 }
21
22 function pkcs8_encode($Modulus,$PublicExponent) {
23         //Encode key sequence
24         $modulus = new ASNValue(ASNValue::TAG_INTEGER);
25         $modulus->SetIntBuffer($Modulus);
26         $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
27         $publicExponent->SetInt($PublicExponent);
28         $keySequenceItems = array($modulus, $publicExponent);
29         $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
30         $keySequence->SetSequence($keySequenceItems);
31         //Encode bit string
32         $bitStringValue = $keySequence->Encode();
33         $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
34         $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
35         $bitString->Value = $bitStringValue;
36         //Encode body
37         $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
38         $body = new ASNValue(ASNValue::TAG_SEQUENCE);
39         $body->Value = $bodyValue;
40         //Get DER encoded public key:
41         $PublicDER = $body->Encode();
42         return $PublicDER;
43 }
44
45
46 function metopem($m,$e) {
47         $der = pkcs8_emcode($m,$e);
48         $key = DerToPem($der,true);
49         return $key;
50 }       
51
52