001: package org.bouncycastle.bcpg;
002:
003: import java.io.*;
004: import java.util.Date;
005:
006: /**
007: * basic packet for a PGP public key
008: */
009: public class PublicKeyPacket extends ContainedPacket implements
010: PublicKeyAlgorithmTags {
011: private int version;
012: private long time;
013: private int validDays;
014: private int algorithm;
015: private BCPGKey key;
016:
017: PublicKeyPacket(BCPGInputStream in) throws IOException {
018: version = in.read();
019: time = ((long) in.read() << 24) | (in.read() << 16)
020: | (in.read() << 8) | in.read();
021:
022: if (version <= 3) {
023: validDays = (in.read() << 8) | in.read();
024: }
025:
026: algorithm = (byte) in.read();
027:
028: switch (algorithm) {
029: case RSA_ENCRYPT:
030: case RSA_GENERAL:
031: case RSA_SIGN:
032: key = new RSAPublicBCPGKey(in);
033: break;
034: case DSA:
035: key = new DSAPublicBCPGKey(in);
036: break;
037: case ELGAMAL_ENCRYPT:
038: case ELGAMAL_GENERAL:
039: key = new ElGamalPublicBCPGKey(in);
040: break;
041: default:
042: throw new IOException(
043: "unknown PGP public key algorithm encountered");
044: }
045: }
046:
047: /**
048: * Construct version 4 public key packet.
049: *
050: * @param algorithm
051: * @param time
052: * @param key
053: */
054: public PublicKeyPacket(int algorithm, Date time, BCPGKey key) {
055: this .version = 4;
056: this .time = time.getTime() / 1000;
057: this .algorithm = algorithm;
058: this .key = key;
059: }
060:
061: public int getVersion() {
062: return version;
063: }
064:
065: public int getAlgorithm() {
066: return algorithm;
067: }
068:
069: public int getValidDays() {
070: return validDays;
071: }
072:
073: public Date getTime() {
074: return new Date(time * 1000);
075: }
076:
077: public BCPGKey getKey() {
078: return key;
079: }
080:
081: public byte[] getEncodedContents() throws IOException {
082: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
083: BCPGOutputStream pOut = new BCPGOutputStream(bOut);
084:
085: pOut.write(version);
086:
087: pOut.write((byte) (time >> 24));
088: pOut.write((byte) (time >> 16));
089: pOut.write((byte) (time >> 8));
090: pOut.write((byte) time);
091:
092: if (version <= 3) {
093: pOut.write((byte) (validDays >> 8));
094: pOut.write((byte) validDays);
095: }
096:
097: pOut.write(algorithm);
098:
099: pOut.writeObject((BCPGObject) key);
100:
101: return bOut.toByteArray();
102: }
103:
104: public void encode(BCPGOutputStream out) throws IOException {
105: out.writePacket(PUBLIC_KEY, getEncodedContents(), true);
106: }
107: }
|