Files
secure-device-demo/springboot-server/src/main/java/com/secure/demo/crypto/RsaUtil.java

62 lines
1.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.secure.demo.crypto;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
/**
* RSA 工具类
*
* 与 Android 端 DeviceCrypto 配套:
* - Android Keystore 生成 RSA-2048 密钥对
* - 私钥在 TEE 中不可导出
* - 公钥上传服务端,用于加密下发数据
*
* 用途:
* - 加密 Recovery Token设备恢复时下发
* - 加密 DEK恢复后逐张照片下发
*/
public class RsaUtil {
private static final String KEY_ALGO = "RSA";
private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
private RsaUtil() {}
/**
* Base64 公钥 → PublicKey 对象
*/
public static PublicKey publicKeyFromBase64(String publicKeyBase64) {
try {
byte[] keyBytes = Base64.getDecoder().decode(publicKeyBase64);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance(KEY_ALGO);
return kf.generatePublic(spec);
} catch (Exception e) {
throw new RuntimeException("Parse RSA public key failed", e);
}
}
/**
* 用设备 RSA 公钥加密数据
*/
public static byte[] encryptWithPublicKey(byte[] data, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e) {
throw new RuntimeException("RSA encrypt failed", e);
}
}
/**
* 用设备 RSA 公钥加密 → Base64 字符串
*/
public static String encryptBase64(byte[] data, PublicKey publicKey) {
return Base64.getEncoder().encodeToString(encryptWithPublicKey(data, publicKey));
}
}