1 // Copyright 2011 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.
5 // Package packet implements parsing and serialization of OpenPGP packets, as
6 // specified in RFC 4880.
13 error_ "crypto/openpgp/error"
18 // readFull is the same as io.ReadFull except that reading zero bytes returns
19 // ErrUnexpectedEOF rather than EOF.
20 func readFull(r io.Reader, buf []byte) (n int, err error) {
21 n, err = io.ReadFull(r, buf)
23 err = io.ErrUnexpectedEOF
28 // readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2.
29 func readLength(r io.Reader) (length int64, isPartial bool, err error) {
31 _, err = readFull(r, buf[:1])
37 length = int64(buf[0])
39 length = int64(buf[0]-192) << 8
40 _, err = readFull(r, buf[0:1])
44 length += int64(buf[0]) + 192
46 length = int64(1) << (buf[0] & 0x1f)
49 _, err = readFull(r, buf[0:4])
53 length = int64(buf[0])<<24 |
61 // partialLengthReader wraps an io.Reader and handles OpenPGP partial lengths.
62 // The continuation lengths are parsed and removed from the stream and EOF is
63 // returned at the end of the packet. See RFC 4880, section 4.2.2.4.
64 type partialLengthReader struct {
70 func (r *partialLengthReader) Read(p []byte) (n int, err error) {
71 for r.remaining == 0 {
75 r.remaining, r.isPartial, err = readLength(r.r)
81 toRead := int64(len(p))
82 if toRead > r.remaining {
86 n, err = r.r.Read(p[:int(toRead)])
87 r.remaining -= int64(n)
88 if n < int(toRead) && err == io.EOF {
89 err = io.ErrUnexpectedEOF
94 // partialLengthWriter writes a stream of data using OpenPGP partial lengths.
95 // See RFC 4880, section 4.2.2.4.
96 type partialLengthWriter struct {
101 func (w *partialLengthWriter) Write(p []byte) (n int, err error) {
103 for power := uint(14); power < 32; power-- {
106 w.lengthByte[0] = 224 + uint8(power)
107 _, err = w.w.Write(w.lengthByte[:])
112 m, err = w.w.Write(p[:l])
125 func (w *partialLengthWriter) Close() error {
127 _, err := w.w.Write(w.lengthByte[:])
134 // A spanReader is an io.LimitReader, but it returns ErrUnexpectedEOF if the
135 // underlying Reader returns EOF before the limit has been reached.
136 type spanReader struct {
141 func (l *spanReader) Read(p []byte) (n int, err error) {
145 if int64(len(p)) > l.n {
150 if l.n > 0 && err == io.EOF {
151 err = io.ErrUnexpectedEOF
156 // readHeader parses a packet header and returns an io.Reader which will return
157 // the contents of the packet. See RFC 4880, section 4.2.
158 func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
160 _, err = io.ReadFull(r, buf[:1])
164 if buf[0]&0x80 == 0 {
165 err = error_.StructuralError("tag byte does not have MSB set")
168 if buf[0]&0x40 == 0 {
170 tag = packetType((buf[0] & 0x3f) >> 2)
171 lengthType := buf[0] & 3
177 lengthBytes := 1 << lengthType
178 _, err = readFull(r, buf[0:lengthBytes])
182 for i := 0; i < lengthBytes; i++ {
184 length |= int64(buf[i])
186 contents = &spanReader{r, length}
191 tag = packetType(buf[0] & 0x3f)
192 length, isPartial, err := readLength(r)
197 contents = &partialLengthReader{
204 contents = &spanReader{r, length}
209 // serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section
211 func serializeHeader(w io.Writer, ptype packetType, length int) (err error) {
215 buf[0] = 0x80 | 0x40 | byte(ptype)
217 buf[1] = byte(length)
219 } else if length < 8384 {
221 buf[1] = 192 + byte(length>>8)
222 buf[2] = byte(length)
226 buf[2] = byte(length >> 24)
227 buf[3] = byte(length >> 16)
228 buf[4] = byte(length >> 8)
229 buf[5] = byte(length)
233 _, err = w.Write(buf[:n])
237 // serializeStreamHeader writes an OpenPGP packet header to w where the
238 // length of the packet is unknown. It returns a io.WriteCloser which can be
239 // used to write the contents of the packet. See RFC 4880, section 4.2.
240 func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) {
242 buf[0] = 0x80 | 0x40 | byte(ptype)
243 _, err = w.Write(buf[:])
247 out = &partialLengthWriter{w: w}
251 // Packet represents an OpenPGP packet. Users are expected to try casting
252 // instances of this interface to specific packet types.
253 type Packet interface {
254 parse(io.Reader) error
257 // consumeAll reads from the given Reader until error, returning the number of
259 func consumeAll(r io.Reader) (n int64, err error) {
264 m, err = r.Read(buf[:])
278 // packetType represents the numeric ids of the different OpenPGP packet types. See
279 // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-2
280 type packetType uint8
283 packetTypeEncryptedKey packetType = 1
284 packetTypeSignature packetType = 2
285 packetTypeSymmetricKeyEncrypted packetType = 3
286 packetTypeOnePassSignature packetType = 4
287 packetTypePrivateKey packetType = 5
288 packetTypePublicKey packetType = 6
289 packetTypePrivateSubkey packetType = 7
290 packetTypeCompressed packetType = 8
291 packetTypeSymmetricallyEncrypted packetType = 9
292 packetTypeLiteralData packetType = 11
293 packetTypeUserId packetType = 13
294 packetTypePublicSubkey packetType = 14
295 packetTypeSymmetricallyEncryptedMDC packetType = 18
298 // Read reads a single OpenPGP packet from the given io.Reader. If there is an
299 // error parsing a packet, the whole packet is consumed from the input.
300 func Read(r io.Reader) (p Packet, err error) {
301 tag, _, contents, err := readHeader(r)
307 case packetTypeEncryptedKey:
308 p = new(EncryptedKey)
309 case packetTypeSignature:
311 case packetTypeSymmetricKeyEncrypted:
312 p = new(SymmetricKeyEncrypted)
313 case packetTypeOnePassSignature:
314 p = new(OnePassSignature)
315 case packetTypePrivateKey, packetTypePrivateSubkey:
316 pk := new(PrivateKey)
317 if tag == packetTypePrivateSubkey {
321 case packetTypePublicKey, packetTypePublicSubkey:
323 if tag == packetTypePublicSubkey {
327 case packetTypeCompressed:
329 case packetTypeSymmetricallyEncrypted:
330 p = new(SymmetricallyEncrypted)
331 case packetTypeLiteralData:
333 case packetTypeUserId:
335 case packetTypeSymmetricallyEncryptedMDC:
336 se := new(SymmetricallyEncrypted)
340 err = error_.UnknownPacketTypeError(tag)
343 err = p.parse(contents)
351 // SignatureType represents the different semantic meanings of an OpenPGP
352 // signature. See RFC 4880, section 5.2.1.
353 type SignatureType uint8
356 SigTypeBinary SignatureType = 0
358 SigTypeGenericCert = 0x10
359 SigTypePersonaCert = 0x11
360 SigTypeCasualCert = 0x12
361 SigTypePositiveCert = 0x13
362 SigTypeSubkeyBinding = 0x18
365 // PublicKeyAlgorithm represents the different public key system specified for
367 // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12
368 type PublicKeyAlgorithm uint8
371 PubKeyAlgoRSA PublicKeyAlgorithm = 1
372 PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2
373 PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3
374 PubKeyAlgoElGamal PublicKeyAlgorithm = 16
375 PubKeyAlgoDSA PublicKeyAlgorithm = 17
378 // CanEncrypt returns true if it's possible to encrypt a message to a public
379 // key of the given type.
380 func (pka PublicKeyAlgorithm) CanEncrypt() bool {
382 case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal:
388 // CanSign returns true if it's possible for a public key of the given type to
390 func (pka PublicKeyAlgorithm) CanSign() bool {
392 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA:
398 // CipherFunction represents the different block ciphers specified for OpenPGP. See
399 // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13
400 type CipherFunction uint8
403 CipherCAST5 CipherFunction = 3
404 CipherAES128 CipherFunction = 7
405 CipherAES192 CipherFunction = 8
406 CipherAES256 CipherFunction = 9
409 // KeySize returns the key size, in bytes, of cipher.
410 func (cipher CipherFunction) KeySize() int {
424 // blockSize returns the block size, in bytes, of cipher.
425 func (cipher CipherFunction) blockSize() int {
429 case CipherAES128, CipherAES192, CipherAES256:
435 // new returns a fresh instance of the given cipher.
436 func (cipher CipherFunction) new(key []byte) (block cipher.Block) {
439 block, _ = cast5.NewCipher(key)
440 case CipherAES128, CipherAES192, CipherAES256:
441 block, _ = aes.NewCipher(key)
446 // readMPI reads a big integer from r. The bit length returned is the bit
447 // length that was specified in r. This is preserved so that the integer can be
448 // reserialized exactly.
449 func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
451 _, err = readFull(r, buf[0:])
455 bitLength = uint16(buf[0])<<8 | uint16(buf[1])
456 numBytes := (int(bitLength) + 7) / 8
457 mpi = make([]byte, numBytes)
458 _, err = readFull(r, mpi)
462 // mpiLength returns the length of the given *big.Int when serialized as an
464 func mpiLength(n *big.Int) (mpiLengthInBytes int) {
465 mpiLengthInBytes = 2 /* MPI length */
466 mpiLengthInBytes += (n.BitLen() + 7) / 8
470 // writeMPI serializes a big integer to w.
471 func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
472 _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)})
474 _, err = w.Write(mpiBytes)
479 // writeBig serializes a *big.Int to w.
480 func writeBig(w io.Writer, i *big.Int) error {
481 return writeMPI(w, uint16(i.BitLen()), i.Bytes())