1 11 package org.eclipse.core.internal.runtime.auth; 12 13 import java.io.UnsupportedEncodingException ; 14 import java.security.MessageDigest ; 15 import java.util.Random ; 16 17 36 public class Cipher { 37 public static final int DECRYPT_MODE = -1; 38 public static final int ENCRYPT_MODE = 1; 39 private static final int RANDOM_SIZE = 16; 40 41 private int mode = 0; 42 private byte[] password = null; 43 44 private byte[] byteStream; 47 private int byteStreamOffset; 48 private MessageDigest digest; 49 private Random random; 50 private final byte[] toDigest; 51 52 61 public Cipher(int mode, String passwordString) { 62 this.mode = mode; 63 try { 64 this.password = passwordString.getBytes("UTF8"); } catch (UnsupportedEncodingException e) { 66 this.password = passwordString.getBytes(); 67 } 68 toDigest = new byte[password.length + RANDOM_SIZE]; 69 } 70 71 78 public byte[] cipher(byte[] data) throws Exception { 79 return transform(data, 0, data.length, mode); 80 } 81 82 92 public byte[] cipher(byte[] data, int off, int len) throws Exception { 93 return transform(data, off, len, mode); 94 } 95 96 103 public byte cipher(byte datum) throws Exception { 104 byte[] data = {datum}; 105 return cipher(data)[0]; 106 } 107 108 114 private byte[] generateBytes() throws Exception { 115 if (digest == null) { 116 digest = MessageDigest.getInstance("SHA"); long seed = 0; 119 for (int i = 0; i < password.length; i++) 120 seed = (seed * 37) + password[i]; 122 random = new Random (seed); 123 } 124 random.nextBytes(toDigest); 126 127 System.arraycopy(password, 0, toDigest, 0, password.length); 129 130 return digest.digest(toDigest); 132 } 133 134 138 private byte[] nextRandom(int length) throws Exception { 139 byte[] nextRandom = new byte[length]; 140 int nextRandomOffset = 0; 141 while (nextRandomOffset < length) { 142 if (byteStream == null || byteStreamOffset >= byteStream.length) { 143 byteStream = generateBytes(); 144 byteStreamOffset = 0; 145 } 146 nextRandom[nextRandomOffset++] = byteStream[byteStreamOffset++]; 147 } 148 return nextRandom; 149 } 150 151 private byte[] transform(byte[] data, int off, int len, int mod) throws Exception { 152 byte[] result = nextRandom(len); 153 for (int i = 0; i < len; ++i) { 154 result[i] = (byte) (data[i + off] + mod * result[i]); 155 } 156 return result; 157 } 158 } 159 | Popular Tags |