当顾客想从 Web 站点购买某个产品时,顾客和 Web 站点都要进行认证。顾客通常是以提供名字和密码的方式来认证他自己。另一方面,Web 站点通过交换一块签名数据和一个有效的 X.509 证书(作为 SSL 握手的一部分)来认证它自己。顾客的浏览器验证该证书并用所附的公用密钥验证签名数据。一旦双方都认证了,则交易就可以开始了。
对等机 A 发起这项事务,每台对等机相互认证,两台对等机协商采用的密码及其长度并建立一个安全通道。完成这些操作之后,每个对等机都知道它正在跟谁交谈并且知道通道是安全的。
初始化 因为 JSSE 和 SSL 的介绍对初始化代码有很大影响,所以让我们来考察对等机 A 中负责初始化的代码。
清单 1. 安全初始化代码 // Each peer has an identity that must be locally (but not globally) // unique. This identity and its associated public and private keys // are stored in a keystore and protected by a passWord. Each // peer also has a name that must be globally unique. String stringIdentity = null; String stringPassword = null; String stringName = null;
// The code that prompts the user for his/her identity // and password goes here. the user´s name is // generated (if necessary) later.
// Create home Directory. This is a very portable way // to create a home directory, but it has its problems -- // the various flavors of Microsoft Windows put the directory // in widely different locations in the directory hierarchy. String stringHome = System.getProperty("user.home") + File.separator + "p2p"; File fileHome = new File(stringHome); if (fileHome.exists() == false) fileHome.mkdirs();
// Create keystore. We must run an external process to create the // keystore, because the security APIs don´t eXPose enough // functionality to do this inline. I haven´t tested this widely enough // to know how portable this code is, but it works on everything I // tried it on. String stringKeyStore = stringHome + File.separator + "keystore"; File fileKeyStore = new File(stringKeyStore); if (fileKeyStore.exists() == false) { System.out.println("Creating keystore..."); byte [] arb = new byte [16]; SecureRandom securerandom = SecureRandom.getInstance("SHA1PRNG"); securerandom.nextBytes(arb); stringName = new String(Base64.encode(arb)); String [] arstringCommand = new String [] { System.getProperty("java.home") + File.separator + "bin" + File.separator + "keytool", "-genkey", "-alias", stringIdentity, "-keyalg", "RSA", "-keysize", "1024", "-dname", "CN=" + stringName, "-keystore", stringHome + File.separator + "keystore", "-keypass", stringPassword, "-storetype", "JCEKS", "-storepass", stringPassword }; Process process = Runtime.getRuntime().exec(arstringCommand); process.waitFor(); InputStream inputstream2 = process.getInputStream(); IOUtils.copy(inputstream2, System.out); InputStream inputstream3 = process.getErrorStream(); IOUtils.copy(inputstream3, System.out); if (process.exitvalue() != 0) System.exit(-1); }
// Once the application has created/located the keystore, it // opens it and creates a KeyStore instance from the data // in it. char [] archPassword = stringPassword.toCharArray(); FileInputStream fileinputstream = new FileInputStream(stringHome + File.separator +