package com.kidshelloworld.secure;
import org.bouncycastle.crypto.agreement.ECDHBasicAgreement;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.engines.IESEngine;
import org.bouncycastle.crypto.generators.KDF2BytesGenerator;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.util.DigestFactory;
import org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class ECIESExample {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static void main(String[] args) throws Exception {
String input = "This is a secret message";
byte[] data = input.getBytes();
String publicKey = "";
String privateKey = "";
byte[] pub = Base64.getDecoder().decode(publicKey);
byte[] pk = Base64.getDecoder().decode(privateKey);
System.out.println("pub key hex: " + Hex.toHexString(pub));
System.out.println("pri key hex: " + Hex.toHexString(pk));
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pub);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
ECPublicKey ecPublicKey = (ECPublicKey)keyFactory.generatePublic(x509EncodedKeySpec);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(pk);
ECPrivateKey ecPrivateKey = (ECPrivateKey)keyFactory.generatePrivate(pkcs8EncodedKeySpec);
// Encrypt the message using ECIES
IESCipher encryptCipher = new IESCipher(new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(DigestFactory.createSHA256()),
new HMac(DigestFactory.createSHA256()),
new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())))
);
encryptCipher.engineInit(Cipher.ENCRYPT_MODE, ecPublicKey, new SecureRandom());
byte[] encryptedData = encryptCipher.engineUpdate(data, 0, data.length);
byte[] result = encryptCipher.engineDoFinal(encryptedData, 0, 0);
String r = Base64.getEncoder().encodeToString(result);
System.out.println(r);
result = Base64.getDecoder().decode(r);
encryptCipher.engineInit(Cipher.DECRYPT_MODE, ecPrivateKey, new SecureRandom());
byte[] decryptedData = encryptCipher.engineUpdate(result, 0, result.length);
result = encryptCipher.engineDoFinal(decryptedData, 0, 0);
System.out.println(new String(result));
}
}
ECIES例子
最新推荐文章于 2024-07-13 13:09:02 发布