blob: 3eb7c9fa0d91a9ee0a7bd872c1d73c4d5f00a4c6 [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"
Adam Langleyfd74a832009-10-21 17:53:50 -070014)
15
16// A Block represents a PEM encoded structure.
17//
18// The encoded form is:
19// -----BEGIN Type-----
20// Headers
21// base64-encoded Bytes
22// -----END Type-----
23// where Headers is a possibly empty sequence of Key: Value lines.
24type Block struct {
Robert Griesemer1c729592009-12-15 15:27:16 -080025 Type string // The type, taken from the preamble (i.e. "RSA PRIVATE KEY").
26 Headers map[string]string // Optional headers.
27 Bytes []byte // The decoded bytes of the contents. Typically a DER encoded ASN.1 structure.
Adam Langleyfd74a832009-10-21 17:53:50 -070028}
29
30// getLine results the first \r\n or \n delineated line from the given byte
31// array. The line does not include the \r\n or \n. The remainder of the byte
32// array (also not including the new line bytes) is also returned and this will
33// always be smaller than the original argument.
34func getLine(data []byte) (line, rest []byte) {
Robert Griesemer1c729592009-12-15 15:27:16 -080035 i := bytes.Index(data, []byte{'\n'})
36 var j int
Adam Langleyfd74a832009-10-21 17:53:50 -070037 if i < 0 {
Robert Griesemer1c729592009-12-15 15:27:16 -080038 i = len(data)
39 j = i
Adam Langleyfd74a832009-10-21 17:53:50 -070040 } else {
Robert Griesemer1c729592009-12-15 15:27:16 -080041 j = i + 1
Adam Langleyfd74a832009-10-21 17:53:50 -070042 if i > 0 && data[i-1] == '\r' {
Robert Griesemer40621d52009-11-09 12:07:39 -080043 i--
Adam Langleyfd74a832009-10-21 17:53:50 -070044 }
45 }
Robert Griesemer1c729592009-12-15 15:27:16 -080046 return data[0:i], data[j:]
Adam Langleyfd74a832009-10-21 17:53:50 -070047}
48
49// removeWhitespace returns a copy of its input with all spaces, tab and
50// newline characters removed.
51func removeWhitespace(data []byte) []byte {
Robert Griesemer1c729592009-12-15 15:27:16 -080052 result := make([]byte, len(data))
53 n := 0
Adam Langleyfd74a832009-10-21 17:53:50 -070054
55 for _, b := range data {
56 if b == ' ' || b == '\t' || b == '\r' || b == '\n' {
Robert Griesemer40621d52009-11-09 12:07:39 -080057 continue
Adam Langleyfd74a832009-10-21 17:53:50 -070058 }
Robert Griesemer1c729592009-12-15 15:27:16 -080059 result[n] = b
60 n++
Adam Langleyfd74a832009-10-21 17:53:50 -070061 }
62
Robert Griesemer1c729592009-12-15 15:27:16 -080063 return result[0:n]
Adam Langleyfd74a832009-10-21 17:53:50 -070064}
65
Russ Cox9750adb2010-02-25 16:01:29 -080066var pemStart = []byte("\n-----BEGIN ")
67var pemEnd = []byte("\n-----END ")
68var pemEndOfLine = []byte("-----")
Adam Langleyfd74a832009-10-21 17:53:50 -070069
70// Decode will find the next PEM formatted block (certificate, private key
71// etc) in the input. It returns that block and the remainder of the input. If
Adam Langley7d680932009-10-21 19:47:52 -070072// no PEM data is found, p is nil and the whole of the input is returned in
73// rest.
Adam Langleyfd74a832009-10-21 17:53:50 -070074func Decode(data []byte) (p *Block, rest []byte) {
75 // pemStart begins with a newline. However, at the very beginning of
76 // the byte array, we'll accept the start string without it.
Robert Griesemer1c729592009-12-15 15:27:16 -080077 rest = data
Russ Cox9ac44492009-11-20 11:45:05 -080078 if bytes.HasPrefix(data, pemStart[1:]) {
Robert Griesemer40621d52009-11-09 12:07:39 -080079 rest = rest[len(pemStart)-1 : len(data)]
Adam Langleyfd74a832009-10-21 17:53:50 -070080 } else if i := bytes.Index(data, pemStart); i >= 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -080081 rest = rest[i+len(pemStart) : len(data)]
Adam Langleyfd74a832009-10-21 17:53:50 -070082 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -080083 return nil, data
Adam Langleyfd74a832009-10-21 17:53:50 -070084 }
85
Robert Griesemer1c729592009-12-15 15:27:16 -080086 typeLine, rest := getLine(rest)
Adam Langleyfd74a832009-10-21 17:53:50 -070087 if !bytes.HasSuffix(typeLine, pemEndOfLine) {
Russ Cox21e75da2011-06-17 06:07:13 -040088 return decodeError(data, rest)
Adam Langleyfd74a832009-10-21 17:53:50 -070089 }
Robert Griesemer1c729592009-12-15 15:27:16 -080090 typeLine = typeLine[0 : len(typeLine)-len(pemEndOfLine)]
Adam Langleyfd74a832009-10-21 17:53:50 -070091
92 p = &Block{
93 Headers: make(map[string]string),
Robert Griesemerf44fa9b2010-03-02 13:46:51 -080094 Type: string(typeLine),
Robert Griesemer1c729592009-12-15 15:27:16 -080095 }
Adam Langleyfd74a832009-10-21 17:53:50 -070096
97 for {
98 // This loop terminates because getLine's second result is
Brad Fitzpatrickdcdaeeb2011-07-13 10:54:51 -070099 // always smaller than its argument.
Adam Langleyfd74a832009-10-21 17:53:50 -0700100 if len(rest) == 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -0800101 return nil, data
Adam Langleyfd74a832009-10-21 17:53:50 -0700102 }
Robert Griesemer1c729592009-12-15 15:27:16 -0800103 line, next := getLine(rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700104
Robert Griesemer1c729592009-12-15 15:27:16 -0800105 i := bytes.Index(line, []byte{':'})
Adam Langleyfd74a832009-10-21 17:53:50 -0700106 if i == -1 {
Robert Griesemer40621d52009-11-09 12:07:39 -0800107 break
Adam Langleyfd74a832009-10-21 17:53:50 -0700108 }
109
110 // TODO(agl): need to cope with values that spread across lines.
Robert Griesemer1c729592009-12-15 15:27:16 -0800111 key, val := line[0:i], line[i+1:]
112 key = bytes.TrimSpace(key)
113 val = bytes.TrimSpace(val)
114 p.Headers[string(key)] = string(val)
115 rest = next
Adam Langleyfd74a832009-10-21 17:53:50 -0700116 }
117
Robert Griesemer1c729592009-12-15 15:27:16 -0800118 i := bytes.Index(rest, pemEnd)
Adam Langleyfd74a832009-10-21 17:53:50 -0700119 if i < 0 {
Russ Cox21e75da2011-06-17 06:07:13 -0400120 return decodeError(data, rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700121 }
Robert Griesemer1c729592009-12-15 15:27:16 -0800122 base64Data := removeWhitespace(rest[0:i])
Adam Langleyfd74a832009-10-21 17:53:50 -0700123
Robert Griesemer1c729592009-12-15 15:27:16 -0800124 p.Bytes = make([]byte, base64.StdEncoding.DecodedLen(len(base64Data)))
125 n, err := base64.StdEncoding.Decode(p.Bytes, base64Data)
Adam Langleyfd74a832009-10-21 17:53:50 -0700126 if err != nil {
Russ Cox21e75da2011-06-17 06:07:13 -0400127 return decodeError(data, rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700128 }
Robert Griesemer1c729592009-12-15 15:27:16 -0800129 p.Bytes = p.Bytes[0:n]
Adam Langleyfd74a832009-10-21 17:53:50 -0700130
Robert Griesemer1c729592009-12-15 15:27:16 -0800131 _, rest = getLine(rest[i+len(pemEnd):])
Adam Langleyfd74a832009-10-21 17:53:50 -0700132
Robert Griesemer1c729592009-12-15 15:27:16 -0800133 return
Russ Cox21e75da2011-06-17 06:07:13 -0400134}
Adam Langleyfd74a832009-10-21 17:53:50 -0700135
Russ Cox21e75da2011-06-17 06:07:13 -0400136func decodeError(data, rest []byte) (*Block, []byte) {
Adam Langleyfd74a832009-10-21 17:53:50 -0700137 // If we get here then we have rejected a likely looking, but
138 // ultimately invalid PEM block. We need to start over from a new
139 // position. We have consumed the preamble line and will have consumed
140 // any lines which could be header lines. However, a valid preamble
141 // line is not a valid header line, therefore we cannot have consumed
142 // the preamble line for the any subsequent block. Thus, we will always
Robert Henckec8727c82011-05-18 13:14:56 -0400143 // find any valid block, no matter what bytes precede it.
Adam Langleyfd74a832009-10-21 17:53:50 -0700144 //
145 // For example, if the input is
146 //
147 // -----BEGIN MALFORMED BLOCK-----
148 // junk that may look like header lines
149 // or data lines, but no END line
150 //
151 // -----BEGIN ACTUAL BLOCK-----
152 // realdata
153 // -----END ACTUAL BLOCK-----
154 //
155 // we've failed to parse using the first BEGIN line
156 // and now will try again, using the second BEGIN line.
Russ Cox21e75da2011-06-17 06:07:13 -0400157 p, rest := Decode(rest)
Adam Langleyfd74a832009-10-21 17:53:50 -0700158 if p == nil {
Robert Griesemer40621d52009-11-09 12:07:39 -0800159 rest = data
Adam Langleyfd74a832009-10-21 17:53:50 -0700160 }
Russ Cox21e75da2011-06-17 06:07:13 -0400161 return p, rest
Adam Langleyfd74a832009-10-21 17:53:50 -0700162}
Adam Langleyd5841ca2010-02-07 15:22:36 -0500163
164const pemLineLength = 64
165
166type lineBreaker struct {
167 line [pemLineLength]byte
168 used int
169 out io.Writer
170}
171
Russ Coxc2049d22011-11-01 22:04:37 -0400172func (l *lineBreaker) Write(b []byte) (n int, err error) {
Adam Langleyd5841ca2010-02-07 15:22:36 -0500173 if l.used+len(b) < pemLineLength {
174 copy(l.line[l.used:], b)
175 l.used += len(b)
176 return len(b), nil
177 }
178
179 n, err = l.out.Write(l.line[0:l.used])
180 if err != nil {
181 return
182 }
183 excess := pemLineLength - l.used
184 l.used = 0
185
186 n, err = l.out.Write(b[0:excess])
187 if err != nil {
188 return
189 }
190
191 n, err = l.out.Write([]byte{'\n'})
192 if err != nil {
193 return
194 }
195
196 return l.Write(b[excess:])
197}
198
Russ Coxc2049d22011-11-01 22:04:37 -0400199func (l *lineBreaker) Close() (err error) {
Adam Langleyd5841ca2010-02-07 15:22:36 -0500200 if l.used > 0 {
201 _, err = l.out.Write(l.line[0:l.used])
202 if err != nil {
203 return
204 }
205 _, err = l.out.Write([]byte{'\n'})
206 }
207
208 return
209}
210
Russ Coxc2049d22011-11-01 22:04:37 -0400211func Encode(out io.Writer, b *Block) (err error) {
Adam Langleyd5841ca2010-02-07 15:22:36 -0500212 _, err = out.Write(pemStart[1:])
213 if err != nil {
214 return
215 }
Russ Cox9750adb2010-02-25 16:01:29 -0800216 _, err = out.Write([]byte(b.Type + "-----\n"))
Adam Langleyd5841ca2010-02-07 15:22:36 -0500217 if err != nil {
218 return
219 }
220
Russ Cox36560d22010-07-12 16:48:49 -0700221 if len(b.Headers) > 0 {
222 for k, v := range b.Headers {
223 _, err = out.Write([]byte(k + ": " + v + "\n"))
224 if err != nil {
225 return
226 }
Adam Langleyd5841ca2010-02-07 15:22:36 -0500227 }
Adam Langleyd5841ca2010-02-07 15:22:36 -0500228 _, err = out.Write([]byte{'\n'})
229 if err != nil {
230 return
231 }
232 }
233
234 var breaker lineBreaker
235 breaker.out = out
236
237 b64 := base64.NewEncoder(base64.StdEncoding, &breaker)
238 _, err = b64.Write(b.Bytes)
239 if err != nil {
240 return
241 }
242 b64.Close()
243 breaker.Close()
244
245 _, err = out.Write(pemEnd[1:])
246 if err != nil {
247 return
248 }
Russ Cox9750adb2010-02-25 16:01:29 -0800249 _, err = out.Write([]byte(b.Type + "-----\n"))
Adam Langleyd5841ca2010-02-07 15:22:36 -0500250 return
251}
252
253func EncodeToMemory(b *Block) []byte {
254 buf := bytes.NewBuffer(nil)
255 Encode(buf, b)
256 return buf.Bytes()
257}