Settting Up the Development Environment
Install Java and Maven on OpenEuler:
sudo yum install java-17-openjdk
sudo yum install maven
Creating the Project Srtucture
- Create a Maven project by adding the following dependencies to pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>CryptoApp</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.77</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-ext-jdk15to18</artifactId>
<version>1.77</version>
</dependency>
</dependencies>
</project>
- Create the following Java files in src/main/java:
CryptoDemo.java:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
public class CryptoDemo {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static void main(String[] args) {
String message = "Sample text for encryption";
String secretKey = CryptoUtils.generateKey();
String encrypted = new CryptoUtils().encryptData(message, secretKey);
System.out.println("Encrypted: " + encrypted);
String decrypted = new CryptoUtils().decryptData(encrypted, secretKey);
System.out.println("Decrypted: " + decrypted);
}
}
CryptoUtils.java:
import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.encoders.Base64;
import java.security.SecureRandom;
public class CryptoUtils {
public static String generateKey() {
byte[] keyData = new byte[16];
new SecureRandom().nextBytes(keyData);
return Base64.toBase64String(keyData);
}
public String encryptData(String input, String key) {
byte[] keyBytes = Base64.decode(key);
byte[] inputBytes = input.getBytes();
byte[] output = new byte[inputBytes.length];
SM4Engine cipher = new SM4Engine();
cipher.init(true, new KeyParameter(keyBytes));
cipher.processBlock(inputBytes, 0, output, 0);
return Hex.toHexString(output);
}
public String decryptData(String encrypted, String key) {
byte[] keyBytes = Base64.decode(key);
byte[] inputBytes = Hex.decode(encrypted);
byte[] output = new byte[inputBytes.length];
SM4Engine cipher = new SM4Engine();
cipher.init(false, new KeyParameter(keyBytes));
cipher.processBlock(inputBytes, 0, output, 0);
return new String(output);
}
}
Building and Running the Application
- Compile the project:
mvn clean package
- Execute the application:
java -cp target/classes:target/CryptoApp-1.0-SNAPSHOT.jar CryptoDemo