blob: ebe57edc0e62672c2f4d3a55c82e4fbea4f05181 [file] [log] [blame]
Adam Langleyfd74a832009-10-21 17:53:50 -07001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Nigel Tao6a186d32011-04-20 09:57:05 +10005// Package pem implements the PEM data encoding, which originated in Privacy
Adam Langleyfd74a832009-10-21 17:53:50 -07006// Enhanced Mail. The most common use of PEM encoding today is in TLS keys and
7// certificates. See RFC 1421.
8package pem
9
10import (
Robert Griesemer1c729592009-12-15 15:27:16 -080011 "bytes"
12 "encoding/base64"
Adam Langleyd5841ca2010-02-07 15:22:36 -050013 "io"
14 "os"
Adam Langleyfd74a832009-10-21 17:53:50 -070015)
16
17// A Block represents a PEM encoded structure.
18//
19// The encoded form is:
20// -----BEGIN Type-----
21// Headers
22// base64-encoded Bytes
23// -----END Type-----
24// where Headers is a possibly empty sequence of Key: Value lines.
25type Block struct {
Robert Griesemer1c729592009-12-15 15:27:16 -080026 Type string // The type, taken from the preamble (i.e. "RSA PRIVATE KEY").
27 Headers map[string]string // Optional headers.
28 Bytes []byte // The decoded bytes of the contents. Typically a DER encoded ASN.1 structure.
Adam Langleyfd74a832009-10-21 17:53:50 -070029}
30
31// getLine results the first \r\n or \n delineated line from the given byte
32// array. The line does not include the \r\n or \n. The remainder of the byte
33// array (also not including the new line bytes) is also returned and this will
34// always be smaller than the original argument.
35func getLine(data []byte) (line, rest []byte) {
Robert Griesemer1c729592009-12-15 15:27:16 -080036 i := bytes.Index(data, []byte{'\n'})
37 var j int
Adam Langleyfd74a832009-10-21 17:53:50 -070038 if i < 0 {
Robert Griesemer1c729592009-12-15 15:27:16 -080039 i = len(data)
40 j = i
Adam Langleyfd74a832009-10-21 17:53:50 -070041 } else {
Robert Griesemer1c729592009-12-15 15:27:16 -080042 j = i + 1
Adam Langleyfd74a832009-10-21 17:53:50 -070043 if i > 0 && data[i-1] == '\r' {
Robert Griesemer40621d52009-11-09 12:07:39 -080044 i--
Adam Langleyfd74a832009-10-21 17:53:50 -070045 }
46 }
Robert Griesemer1c729592009-12-15 15:27:16 -080047 return data[0:i], data[j:]
Adam Langleyfd74a832009-10-21 17:53:50 -070048}
49
50// removeWhitespace returns a copy of its input with all spaces, tab and
51// newline characters removed.
52func removeWhitespace(data []byte) []byte {
Robert Griesemer1c729592009-12-15 15:27:16 -080053 result := make([]byte, len(data))
54 n := 0
Adam Langleyfd74a832009-10-21 17:53:50 -070055
56 for _, b := range data {
57 if b == ' ' || b == '\t' || b == '\r' || b == '\n' {
Robert Griesemer40621d52009-11-09 12:07:39 -080058 continue
Adam Langleyfd74a832009-10-21 17:53:50 -070059 }
Robert Griesemer1c729592009-12-15 15:27:16 -080060 result[n] = b
61 n++
Adam Langleyfd74a832009-10-21 17:53:50 -070062 }
63
Robert Griesemer1c729592009-12-15 15:27:16 -080064 return result[0:n]
Adam Langleyfd74a832009-10-21 17:53:50 -070065}
66
Russ Cox9750adb2010-02-25 16:01:29 -080067var pemStart = []byte("\n-----BEGIN ")
68var pemEnd = []byte("\n-----END ")
69var pemEndOfLine = []byte("-----")
Adam Langleyfd74a832009-10-21 17:53:50 -070070
71// Decode will find the next PEM formatted block (certificate, private key
72// etc) in the input. It returns that block and the remainder of the input. If
Adam Langley7d680932009-10-21 19:47:52 -070073// no PEM data is found, p is nil and the whole of the input is returned in
74// rest.
Adam Langleyfd74a832009-10-21 17:53:50 -070075func Decode(data []byte) (p *Block, rest []byte) {
76 // pemStart begins with a newline. However, at the very beginning of
77 // the byte array, we'll accept the start string without it.
Robert Griesemer1c729592009-12-15 15:27:16 -080078 rest = data
Russ Cox9ac44492009-11-20 11:45:05 -080079 if bytes.HasPrefix(data, pemStart[1:]) {
Robert Griesemer40621d52009-11-09 12:07:39 -080080 rest = rest[len(pemStart)-1 : len(data)]
Adam Langleyfd74a832009-10-21 17:53:50 -070081 } else if i := bytes.Index(data, pemStart); i >= 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -080082 rest = rest[i+len(pemStart) : len(data)]
Adam Langleyfd74a832009-10-21 17:53:50 -070083 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -080084 return nil, data
Adam Langleyfd74a832009-10-21 17:53:50 -070085 }
86
Robert Griesemer1c729592009-12-15 15:27:16 -080087 typeLine, rest := getLine(rest)
Adam Langleyfd74a832009-10-21 17:53:50 -070088 if !bytes.HasSuffix(typeLine, pemEndOfLine) {
Russ Cox21e75da2011-06-17 06:07:13 -040089 return decodeError(data, rest)
Adam Langleyfd74a832009-10-21 17:53:50 -070090 }
Robert Griesemer1c729592009-12-15 15:27:16 -080091 typeLine = typeLine[0 : len(typeLine)-len(pemEndOfLine)]
Adam Langleyfd74a832009-10-21 17:53:50 -070092
93 p = &Block{
94 Headers: make(map[string]string),
Robert Griesemerf44fa9b2010-03-02 13:46:51 -080095 Type: string(typeLine),
Robert Griesemer1c729592009-12-15 15:27:16 -080096 }
Adam Langleyfd74a832009-10-21 17:53:50 -070097
98 for {
99 // This loop terminates because getLine's second result is
100 // always smaller than it's argument.
101 if len(rest) == 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -0800102 return nil, data
Adam Langleyfd74a832009-10-21 17:53:50 -0700103 }
Robert Griesemer1c729592009-12-15 15:27:16 -0800104 line, next := getLine(rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700105
Robert Griesemer1c729592009-12-15 15:27:16 -0800106 i := bytes.Index(line, []byte{':'})
Adam Langleyfd74a832009-10-21 17:53:50 -0700107 if i == -1 {
Robert Griesemer40621d52009-11-09 12:07:39 -0800108 break
Adam Langleyfd74a832009-10-21 17:53:50 -0700109 }
110
111 // TODO(agl): need to cope with values that spread across lines.
Robert Griesemer1c729592009-12-15 15:27:16 -0800112 key, val := line[0:i], line[i+1:]
113 key = bytes.TrimSpace(key)
114 val = bytes.TrimSpace(val)
115 p.Headers[string(key)] = string(val)
116 rest = next
Adam Langleyfd74a832009-10-21 17:53:50 -0700117 }
118
Robert Griesemer1c729592009-12-15 15:27:16 -0800119 i := bytes.Index(rest, pemEnd)
Adam Langleyfd74a832009-10-21 17:53:50 -0700120 if i < 0 {
Russ Cox21e75da2011-06-17 06:07:13 -0400121 return decodeError(data, rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700122 }
Robert Griesemer1c729592009-12-15 15:27:16 -0800123 base64Data := removeWhitespace(rest[0:i])
Adam Langleyfd74a832009-10-21 17:53:50 -0700124
Robert Griesemer1c729592009-12-15 15:27:16 -0800125 p.Bytes = make([]byte, base64.StdEncoding.DecodedLen(len(base64Data)))
126 n, err := base64.StdEncoding.Decode(p.Bytes, base64Data)
Adam Langleyfd74a832009-10-21 17:53:50 -0700127 if err != nil {
Russ Cox21e75da2011-06-17 06:07:13 -0400128 return decodeError(data, rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700129 }
Robert Griesemer1c729592009-12-15 15:27:16 -0800130 p.Bytes = p.Bytes[0:n]
Adam Langleyfd74a832009-10-21 17:53:50 -0700131
Robert Griesemer1c729592009-12-15 15:27:16 -0800132 _, rest = getLine(rest[i+len(pemEnd):])
Adam Langleyfd74a832009-10-21 17:53:50 -0700133
Robert Griesemer1c729592009-12-15 15:27:16 -0800134 return
Russ Cox21e75da2011-06-17 06:07:13 -0400135}
Adam Langleyfd74a832009-10-21 17:53:50 -0700136
Russ Cox21e75da2011-06-17 06:07:13 -0400137func decodeError(data, rest []byte) (*Block, []byte) {
Adam Langleyfd74a832009-10-21 17:53:50 -0700138 // If we get here then we have rejected a likely looking, but
139 // ultimately invalid PEM block. We need to start over from a new
140 // position. We have consumed the preamble line and will have consumed
141 // any lines which could be header lines. However, a valid preamble
142 // line is not a valid header line, therefore we cannot have consumed
143 // the preamble line for the any subsequent block. Thus, we will always
Robert Henckec8727c82011-05-18 13:14:56 -0400144 // find any valid block, no matter what bytes precede it.
Adam Langleyfd74a832009-10-21 17:53:50 -0700145 //
146 // For example, if the input is
147 //
148 // -----BEGIN MALFORMED BLOCK-----
149 // junk that may look like header lines
150 // or data lines, but no END line
151 //
152 // -----BEGIN ACTUAL BLOCK-----
153 // realdata
154 // -----END ACTUAL BLOCK-----
155 //
156 // we've failed to parse using the first BEGIN line
157 // and now will try again, using the second BEGIN line.
Russ Cox21e75da2011-06-17 06:07:13 -0400158 p, rest := Decode(rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700159 if p == nil {
Robert Griesemer40621d52009-11-09 12:07:39 -0800160 rest = data
Adam Langleyfd74a832009-10-21 17:53:50 -0700161 }
Russ Cox21e75da2011-06-17 06:07:13 -0400162 return p, rest
Adam Langleyfd74a832009-10-21 17:53:50 -0700163}
Adam Langleyd5841ca2010-02-07 15:22:36 -0500164
165const pemLineLength = 64
166
167type lineBreaker struct {
168 line [pemLineLength]byte
169 used int
170 out io.Writer
171}
172
173func (l *lineBreaker) Write(b []byte) (n int, err os.Error) {
174 if l.used+len(b) < pemLineLength {
175 copy(l.line[l.used:], b)
176 l.used += len(b)
177 return len(b), nil
178 }
179
180 n, err = l.out.Write(l.line[0:l.used])
181 if err != nil {
182 return
183 }
184 excess := pemLineLength - l.used
185 l.used = 0
186
187 n, err = l.out.Write(b[0:excess])
188 if err != nil {
189 return
190 }
191
192 n, err = l.out.Write([]byte{'\n'})
193 if err != nil {
194 return
195 }
196
197 return l.Write(b[excess:])
198}
199
200func (l *lineBreaker) Close() (err os.Error) {
201 if l.used > 0 {
202 _, err = l.out.Write(l.line[0:l.used])
203 if err != nil {
204 return
205 }
206 _, err = l.out.Write([]byte{'\n'})
207 }
208
209 return
210}
211
212func Encode(out io.Writer, b *Block) (err os.Error) {
213 _, err = out.Write(pemStart[1:])
214 if err != nil {
215 return
216 }
Russ Cox9750adb2010-02-25 16:01:29 -0800217 _, err = out.Write([]byte(b.Type + "-----\n"))
Adam Langleyd5841ca2010-02-07 15:22:36 -0500218 if err != nil {
219 return
220 }
221
Russ Cox36560d22010-07-12 16:48:49 -0700222 if len(b.Headers) > 0 {
223 for k, v := range b.Headers {
224 _, err = out.Write([]byte(k + ": " + v + "\n"))
225 if err != nil {
226 return
227 }
Adam Langleyd5841ca2010-02-07 15:22:36 -0500228 }
Adam Langleyd5841ca2010-02-07 15:22:36 -0500229 _, err = out.Write([]byte{'\n'})
230 if err != nil {
231 return
232 }
233 }
234
235 var breaker lineBreaker
236 breaker.out = out
237
238 b64 := base64.NewEncoder(base64.StdEncoding, &breaker)
239 _, err = b64.Write(b.Bytes)
240 if err != nil {
241 return
242 }
243 b64.Close()
244 breaker.Close()
245
246 _, err = out.Write(pemEnd[1:])
247 if err != nil {
248 return
249 }
Russ Cox9750adb2010-02-25 16:01:29 -0800250 _, err = out.Write([]byte(b.Type + "-----\n"))
Adam Langleyd5841ca2010-02-07 15:22:36 -0500251 return
252}
253
254func EncodeToMemory(b *Block) []byte {
255 buf := bytes.NewBuffer(nil)
256 Encode(buf, b)
257 return buf.Bytes()
258}