01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.samples;
07:
08: import java.sql.Connection;
09: import java.sql.DriverManager;
10: import java.sql.PreparedStatement;
11: import java.sql.ResultSet;
12: import java.sql.Statement;
13: import java.util.Properties;
14:
15: /**
16: * This example shows how to secure passwords
17: * (both database passwords, and account passwords).
18: */
19: public class SecurePassword {
20:
21: public static void main(String[] argv) throws Exception {
22:
23: Class.forName("org.h2.Driver");
24: String url = "jdbc:h2:data/simple";
25: String user = "sam";
26: char[] password = { 't', 'i', 'a', 'E', 'T', 'r', 'p' };
27:
28: // This is the normal, but 'unsafe' way to connect:
29: // the password may reside in the main memory for an undefined time,
30: // or even written to disk (swap file):
31: // Connection conn =
32: // DriverManager.getConnection(url, user, new String(password));
33:
34: // This is the most safe way to connect: the password is overwritten after use
35: Properties prop = new Properties();
36: prop.setProperty("user", user);
37: prop.put("password", password);
38: Connection conn = DriverManager.getConnection(url, prop);
39:
40: // For security reasons, account passwords should not be stored directly
41: // in a database. Instead, only the hash should be stored. Also,
42: // PreparedStatements must be used to avoid SQL injection:
43: Statement stat = conn.createStatement();
44: stat.execute("drop table account if exists");
45: stat
46: .execute("create table account(name varchar primary key, salt binary default secure_rand(16), hash binary)");
47: PreparedStatement prep;
48: prep = conn
49: .prepareStatement("insert into account(name) values(?)");
50: prep.setString(1, "Joe");
51: prep.execute();
52: prep = conn
53: .prepareStatement("update account set hash=hash('SHA256', stringtoutf8(salt||?), 10) where name=?");
54: prep.setString(1, "secret");
55: prep.setString(2, "Joe");
56: prep.execute();
57: prep = conn
58: .prepareStatement("select * from account where name=? and hash=hash('SHA256', stringtoutf8(salt||?), 10)");
59: prep.setString(1, "Joe");
60: prep.setString(2, "secret");
61: ResultSet rs = prep.executeQuery();
62: while (rs.next()) {
63: System.out.println(rs.getString("name"));
64: }
65: conn.close();
66: }
67:
68: }
|