現代のアプリケーション開発において、機密情報の保護は必須の課題です。データ脱敏は、ユーザー情報のプライバシーを確保しつつ、システムの正常な動作を維持するための有効な手法です。本稿では、Spring Bootアプリケーションでデータ脱敏を実装する方法を説明します。
まず、必要な依存関係をpom.xmlに追加します。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
次に、機密情報を保持するエンティティを定義します。
package com.example.masking.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class PersonalData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long recordId;
private String fullName;
private String contactNumber;
private String idNumber;
// getters/setters
}
脱敏処理を実行するユーティリティクラスを実装します。
package com.example.masking.util;
public class DataObfuscator {
public static String obfuscateContact(String number) {
if (number == null || number.length() < 8) return number;
return number.substring(0, 4) + "****" + number.substring(8);
}
public static String obfuscateId(String id) {
if (id == null || id.length() < 10) return id;
return id.substring(0, 3) + "******" + id.substring(id.length() - 3);
}
}
JSONシリアライゼーションのカスタム処理を実装します。
package com.example.masking.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.example.masking.util.DataObfuscator;
import java.io.IOException;
public class ContactSerializer extends JsonSerializer<String> {
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(DataObfuscator.obfuscateContact(value));
}
}
APIエンドポイントを実装し、脱敏データを返します。
package com.example.masking.controller;
import com.example.masking.entity.PersonalData;
import com.example.masking.repository.DataRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DataController {
private final DataRepository repository;
public DataController(DataRepository repository) {
this.repository = repository;
}
@GetMapping("/data")
public PersonalData getData(@RequestParam Long id) {
return repository.findById(id).orElse(null);
}
}