1 7 8 package java.security; 9 10 import java.io.*; 11 12 import java.security.spec.PKCS8EncodedKeySpec ; 13 import java.security.spec.X509EncodedKeySpec ; 14 import java.security.spec.InvalidKeySpecException ; 15 16 import javax.crypto.SecretKeyFactory; 17 import javax.crypto.spec.SecretKeySpec; 18 19 39 40 public class KeyRep implements Serializable { 41 42 private static final long serialVersionUID = -4757683898830641853L; 43 44 49 public static enum Type { 50 51 52 SECRET, 53 54 55 PUBLIC, 56 57 58 PRIVATE, 59 60 } 61 62 private static final String PKCS8 = "PKCS#8"; 63 private static final String X509 = "X.509"; 64 private static final String RAW = "RAW"; 65 66 71 private Type type; 72 73 78 private String algorithm; 79 80 85 private String format; 86 87 92 private byte[] encoded; 93 94 113 public KeyRep(Type type, String algorithm, 114 String format, byte[] encoded) { 115 116 if (type == null || algorithm == null || 117 format == null || encoded == null) { 118 throw new NullPointerException ("invalid null input(s)"); 119 } 120 121 this.type = type; 122 this.algorithm = algorithm; 123 this.format = format.toUpperCase(); 124 this.encoded = (byte[])encoded.clone(); 125 } 126 127 151 protected Object readResolve() throws ObjectStreamException { 152 try { 153 if (type == Type.SECRET && RAW.equals(format)) { 154 return new SecretKeySpec(encoded, algorithm); 155 } else if (type == Type.PUBLIC && X509.equals(format)) { 156 KeyFactory f = KeyFactory.getInstance(algorithm); 157 return f.generatePublic(new X509EncodedKeySpec (encoded)); 158 } else if (type == Type.PRIVATE && PKCS8.equals(format)) { 159 KeyFactory f = KeyFactory.getInstance(algorithm); 160 return f.generatePrivate(new PKCS8EncodedKeySpec (encoded)); 161 } else { 162 throw new NotSerializableException 163 ("unrecognized type/format combination: " + 164 type + "/" + format); 165 } 166 } catch (NotSerializableException nse) { 167 throw nse; 168 } catch (Exception e) { 169 NotSerializableException nse = new NotSerializableException 170 ("java.security.Key: " + 171 "[" + type + "] " + 172 "[" + algorithm + "] " + 173 "[" + format + "]"); 174 nse.initCause(e); 175 throw nse; 176 } 177 } 178 } 179 | Popular Tags |