Android SM2加密解密
时间: 2024-01-23 11:15:28 浏览: 205
SM2 加密解密
4星 · 用户满意度95%
Android中使用SM2算法进行加密解密的步骤如下:
1. 导入相关库和类:
```java
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.bouncycastle.util.encoders.Base64;
import java.security.Security;
```
2. 初始化BouncyCastleProvider:
```java
Security.addProvider(new BouncyCastleProvider());
```
3. 生成密钥对:
```java
ECKeyPairGenerator generator = new ECKeyPairGenerator();
ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(SM2NamedCurves.getByName("sm2p256v1"), new SecureRandom());
generator.init(keyGenParams);
AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate();
ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic();
```
4. 将公钥和私钥转换为字符串形式:
```java
String privateKeyStr = Base64.toBase64String(privateKey.getD().toByteArray());
String publicKeyStr = Base64.toBase64String(publicKey.getQ().getEncoded(false));
```
5. 加密数据:
```java
String plainText = "Hello, World!";
byte[] plainBytes = plainText.getBytes("UTF-8");
CipherParameters encryptParams = new ParametersWithRandom(publicKey, new SecureRandom());
SM2Engine engine = new SM2Engine();
engine.init(true, encryptParams);
byte[] cipherBytes = engine.processBlock(plainBytes, 0, plainBytes.length);
String cipherText = Base64.toBase64String(cipherBytes);
```
6. 解密数据:
```java
byte[] cipherBytes = Base64.decode(cipherText);
CipherParameters decryptParams = new ParametersWithRandom(privateKey, new SecureRandom());
engine.init(false, decryptParams);
byte[] decryptedBytes = engine.processBlock(cipherBytes, 0, cipherBytes.length);
String decryptedText = new String(decryptedBytes, "UTF-8");
```
注意:以上代码仅为示例,实际使用时需要根据具体情况进行适当的修改和处理。
阅读全文