IK.AM

@making's tech note


Spring Securityの暗号化・復号ユーティリティ

🗃 {Programming/Java/org/springframework/security}
🏷 Java 🏷 Spring Security 
🗓 Updated at 2015-01-20T04:48:12Z  🗓 Created at 2015-01-20T04:48:12Z   🌎 English Page

Spring Securityの提供機能は認証・認可がメインですが、暗号化・復号のユーティリティも入っています。用途やインタフェースが限られている分、何も考えずに使えます。

http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle/#crypto

暗号化・復号

アルゴリズムは 256-bit AES using PKCS #5’s PBKDF2 (Password-Based Key Derivation Function #2) のみ提供しており、インタフェースとして以下の二つが用意されています。

↓が必要 http://qiita.com/mizuki_takahashi/items/cc26a7fd51aa04396e92

ByteEncryptor

byte配列を暗号化してbyte配列を返すインタフェースです。

ByteEncryptor encryptor = Encryptors.standard("password" /* secret key; should not be shared */ , salt);

// 暗号化
byte[] encrypted = encryptor.encrypt(rawBytes);
// 復号
byte[] decrypted = encryptor.decrypt(encrypted);

saltは8-byteのhex文字列で、

String salt = KeyGenerators.string().generateKey(); // SecureRandomの値をhex化

のように生成できます。

TextEncryptor

文字列を暗号化して文字列を返すインタフェースです。

TextEncryptor encryptor = Encryptors.text("password", salt);
TextEncryptor encryptor = Encryptors.queryableText("password", salt);

の2種類があります。

// 暗号化
String encrypted = encryptor.encrypt(rawBytes);
// 復号
String decrypted = encryptor.decrypt(encrypted);

textqueryableTextの違いは初期化ベクトルがランダムか固定かです。 後者は固定のため、セキュリティ強度は墜ちますが、encryptの結果が同じ値を返すため、 検索など、復号せずに暗号化状態で文字列を突合せる用途に用いられるようです。

疑似乱数生成

SecureRandomをつかって乱数を生成します。

BytesKeyGenerator

byte配列で乱数を返します。

KeyGenerator generator = KeyGenerators.secureRandom();
byte[] key = generator.generateKey();

デフォルトは8bytesで、バイト数を指定できます。

KeyGenerator generator = KeyGenerators.secureRandom(16);

常に同じ値を返すGeneratorも作成できます。

KeyGenerator generator = KeyGenerators.secureRandom(16);
byte[] key1 = generator.generateKey();
byte[] key2 = generator.generateKey();

key1とkey2は別

KeyGenerator generator = KeyGenerators.shared(16);
byte[] key1 = generator.generateKey();
byte[] key2 = generator.generateKey();

key1とkey2は同じ

StringKeyGenerator

文字列で乱数を返します。

StringKeyGenerator generator = KeyGenerators.string();
String key = generator.generateKey();

8bytesのHEX文字列(16文字)を返します。


✒️️ Edit  ⏰ History  🗑 Delete