001: package org.bouncycastle.bcpg;
002:
003: import java.io.*;
004:
005: /**
006: * The string to key specifier class
007: */
008: public class S2K extends BCPGObject {
009: private static final int EXPBIAS = 6;
010:
011: public static final int SIMPLE = 0;
012: public static final int SALTED = 1;
013: public static final int SALTED_AND_ITERATED = 3;
014: public static final int GNU_DUMMY_S2K = 101;
015:
016: int type;
017: int algorithm;
018: byte[] iv;
019: int itCount = -1;
020: int protectionMode = -1;
021:
022: S2K(InputStream in) throws IOException {
023: DataInputStream dIn = new DataInputStream(in);
024:
025: type = dIn.read();
026: algorithm = dIn.read();
027:
028: //
029: // if this happens we have a dummy-S2K packet.
030: //
031: if (type != GNU_DUMMY_S2K) {
032: if (type != 0) {
033: iv = new byte[8];
034: dIn.readFully(iv, 0, iv.length);
035: }
036:
037: if (type == 3) {
038: itCount = dIn.read();
039: }
040: } else {
041: dIn.read(); // G
042: dIn.read(); // N
043: dIn.read(); // U
044: protectionMode = dIn.read(); // protection mode
045: }
046: }
047:
048: public S2K(int algorithm) {
049: this .type = 0;
050: this .algorithm = algorithm;
051: }
052:
053: public S2K(int algorithm, byte[] iv) {
054: this .type = 1;
055: this .algorithm = algorithm;
056: this .iv = iv;
057: }
058:
059: public S2K(int algorithm, byte[] iv, int itCount) {
060: this .type = 3;
061: this .algorithm = algorithm;
062: this .iv = iv;
063: this .itCount = itCount;
064: }
065:
066: public int getType() {
067: return type;
068: }
069:
070: /**
071: * return the hash algorithm for this S2K
072: */
073: public int getHashAlgorithm() {
074: return algorithm;
075: }
076:
077: /**
078: * return the iv for the key generation algorithm
079: */
080: public byte[] getIV() {
081: return iv;
082: }
083:
084: /**
085: * return the iteration count
086: */
087: public long getIterationCount() {
088: return (16 + (itCount & 15)) << ((itCount >> 4) + EXPBIAS);
089: }
090:
091: /**
092: * the protection mode - only if GNU_DUMMY_S2K
093: */
094: public int getProtectionMode() {
095: return protectionMode;
096: }
097:
098: public void encode(BCPGOutputStream out) throws IOException {
099: out.write(type);
100: out.write(algorithm);
101:
102: if (type != GNU_DUMMY_S2K) {
103: if (type != 0) {
104: out.write(iv);
105: }
106:
107: if (type == 3) {
108: out.write(itCount);
109: }
110: } else {
111: out.write('G');
112: out.write('N');
113: out.write('U');
114: out.write(protectionMode);
115: }
116: }
117: }
|