1 16 17 package de.schlichtherle.crypto.io.raes; 18 19 import de.schlichtherle.crypto.io.CipherReadOnlyFile; 20 import de.schlichtherle.io.rof.FilterReadOnlyFile; 21 import de.schlichtherle.io.rof.ReadOnlyFile; 22 import de.schlichtherle.io.rof.SimpleReadOnlyFile; 23 24 import java.io.File ; 25 import java.io.FileNotFoundException ; 26 import java.io.IOException ; 27 28 69 public abstract class RaesReadOnlyFile 70 extends CipherReadOnlyFile 71 implements RAES { 72 73 static final int parseUByte(final byte[] bytes, final int offset) { 74 return bytes[offset] & 0xFF; 75 } 76 77 static final int parseUShort(final byte[] bytes, final int offset) { 78 return ((bytes[offset + 1] & 0xFF) << 8) | (bytes[offset] & 0xFF); 79 } 80 81 static final long parseUInt(final byte[] bytes, int offset) { 82 offset += 3; 83 long v = bytes[offset--] & 0xFFl; 84 v <<= 8; 85 v |= bytes[offset--] & 0xFFl; 86 v <<= 8; 87 v |= bytes[offset--] & 0xFFl; 88 v <<= 8; 89 v |= bytes[offset] & 0xFFl; 90 return v; 91 } 92 93 113 public static RaesReadOnlyFile getInstance( 114 final File file, 115 final RaesParameters parameters) 116 throws FileNotFoundException , 117 RaesParametersException, 118 RaesException, 119 IOException { 120 final ReadOnlyFile rof = new SimpleReadOnlyFile(file); 121 try { 122 return getInstance(rof, parameters); 123 } catch (IOException failure) { 124 rof.close(); 125 throw failure; 126 } 127 } 128 129 149 public static RaesReadOnlyFile getInstance( 150 final ReadOnlyFile rof, 151 RaesParameters parameters) 152 throws FileNotFoundException , 153 RaesParametersException, 154 RaesException, 155 IOException { 156 final byte[] leadIn = new byte[LEAD_IN_LENGTH]; 158 rof.seek(0); 159 rof.readFully(leadIn); 160 161 if (parseUInt(leadIn, 0) != RAES_SIGNATURE) 163 throw new RaesException("No RAES signature!"); 164 final int type = parseUByte(leadIn, 4); 165 switch (type) { 166 case 0: 167 parameters = getParameters(Type0RaesParameters.class, parameters); 168 return new Type0RaesReadOnlyFile( 169 rof, (Type0RaesParameters) parameters); 170 171 default: 172 throw new RaesException("Unknown RAES type: " + type); 173 } 174 } 175 176 private static RaesParameters getParameters( 177 final Class type, 178 final RaesParameters parameters) 179 throws RaesParametersException { 180 if (parameters == null) { 182 throw new RaesParametersException(); 183 } else if (type.isAssignableFrom(parameters.getClass())) { 184 return parameters; 185 } else if (parameters instanceof RaesParametersAgent) { 186 return getParameters(type, 187 ((RaesParametersAgent) parameters).getParameters(type)); 188 } else { 189 throw new RaesParametersException(); 190 } 191 } 192 193 RaesReadOnlyFile(ReadOnlyFile rof) { 194 super(rof); 195 } 196 197 201 public abstract int getKeySizeBits(); 202 203 217 public abstract void authenticate() 218 throws RaesAuthenticationException, IOException ; 219 } 220 | Popular Tags |