This guide shows how to enable
data encryption in
H2 database when using it with
Spring Boot for improved security.
1. Add Dependencies
In
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure Encrypted H2 Database
In
application.properties:
spring.datasource.url=jdbc:h2:file:./data/securedb;CIPHER=AES
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=filepwd userpwd
spring.jpa.hibernate.ddl-auto=update
Explanation:
CIPHER=AES → enables AES encryption.
filepwd → encryption password for database file.
userpwd → login password for the DB user.
3. Create Entity
@Entity
public class Secret {
@Id @GeneratedValue
private Long id;
private String message;
}
4. Repository
public interface SecretRepository extends JpaRepository<Secret, Long> {}
5. Save Encrypted Data
@SpringBootTest
class SecretRepoTest {
@Autowired SecretRepository repo;
@Test
void testEncryption() {
repo.save(new Secret(null, "Top Secret Message"));
}
}
The message is stored in an
encrypted H2 file.
6. Verify
Check the
./data/securedb.mv.db file.
It will be encrypted and unreadable without the correct password.
image quote pre code