| 1 package com.quadcap.sql.file; 2 3 7 8 import java.io.IOException ; 9 10 import java.nio.ByteBuffer ; 11 12 import com.quadcap.crypto.Digest; 13 import com.quadcap.crypto.Key; 14 import com.quadcap.crypto.KeyFactory; 15 import com.quadcap.crypto.SymmetricKey; 16 17 22 public class EncryptedBlockStore extends BlockStore { 23 SymmetricKey key; 24 Key encrypt; 25 Key decrypt; 26 byte[] buf0; 27 ByteBuffer b0; 28 29 37 public EncryptedBlockStore() { 38 } 39 40 static final int oHASH_PASSWD_start = BlockFile.oHASH_PASSWD_start; 41 static final int oHASH_PASSWD_len = BlockFile.oHASH_PASSWD_len; 42 43 public void setKey(SymmetricKey key) throws IOException { 44 this.key = key; 45 this.encrypt = key.getEncryptionKey(); 46 this.decrypt = key.getDecryptionKey(); 47 this.buf0 = new byte[blockSize]; 48 b0 = ByteBuffer.wrap(buf0); 49 byte[] digest = makeDigest(key.toString()); 50 if (!isEncrypted()) { 51 synchronized (lock) { 52 buf0[0] = 0x0e; fra.write(0, buf0, 0, 1); 54 fra.write(oHASH_PASSWD_start, digest, 0, digest.length); 55 } 56 } else { 57 synchronized (lock) { 58 fra.read(oHASH_PASSWD_start, buf0, 0, oHASH_PASSWD_len); 59 for (int i = 0; i < digest.length; i++) { 60 if (digest[i] != buf0[i]) { 61 throw new IOException ("Bad username/password"); 62 } 63 } 64 } 65 } 66 } 67 68 byte[] makeDigest(String s) { 69 Digest d = KeyFactory.createDigest("SHA1"); 70 for (int i = 0; i < s.length(); i++) { 71 char c = s.charAt(i); 72 d.update((byte)((c >> 8) & 0xff)); 73 d.update((byte)(c & 0xff)); 74 } 75 return d.digest(); 76 } 77 78 85 public void read(long blockNum, byte[] buf) 86 throws IOException  87 { 88 synchronized (lock) { 89 if (blockNum != 0 && decrypt != null) { 90 super.read(blockNum, buf0); 91 b0.rewind(); 92 decrypt.f(b0, ByteBuffer.wrap(buf)); 93 } else { 94 super.read(blockNum, buf); 95 } 96 } 97 } 98 99 106 public void write(long blockNum, byte[] buf) 107 throws IOException  108 { 109 synchronized (lock) { 110 if (blockNum != 0 && encrypt != null) { 111 b0.clear(); 112 encrypt.f(ByteBuffer.wrap(buf), b0); 113 super.write(blockNum, buf0); 114 } else { 115 super.write(blockNum, buf); 116 } 117 } 118 } 119 } 120 | Popular Tags |