1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

class MyObject extends DataObject {

	private static $db = array(
		'Username' => 'Varchar(255)',
		'Password' => 'Text',
		'Salt' => 'Varchar(60)'
	);

	private static $protected_fields = array(
		'Password'
	);

	private static $private_salt = "*****";

	/**
	 * Encrypt the given field if it's in the $protected_fields array
	 * 
	 * @param string $fieldName
	 * @param string $val
	 * @return DataObject
	 */
	public function setField($fieldName, $val) {
		parent::setField($fieldName, $val);
		
		if (in_array($fieldName, self::$protected_fields)) {
			if ( ! $this->Salt) {
				$this->Salt = EncryptionHelper::createSalt();
			}
			$this->record[$fieldName] = EncryptionHelper::encrypt($val, $this->Salt, self::$private_salt);
		}

		return $this;
	}

	/**
	 * Decrypt the given field if it's in the $protected_fields array
	 * 
	 * @param string $fieldName
	 * @return mixed
	 */
	public function getField($fieldName) {
		if ($val = parent::getField($fieldName)) {
			if (in_array($fieldName, self::$protected_fields) && $this->Salt) {
				return EncryptionHelper::decrypt($val, $this->Salt, self::$private_salt);
			} else {
				return $val;
			}
		}

		return null;
	}

	/**
	 * Ensure we always have a salt to play with
	 * 
	 * @return void
	 */
	public function onBeforeWrite() {
		if ( ! $this->Salt) {
			$this->Salt = EncryptionHelper::createSalt();
		}

		parent::onBeforeWrite();		
	}

}