Java 分别使用椭圆曲线密码对文本消息进行加密和解密
我有这段代码,它同时使用椭圆曲线密码对文本消息进行加密和解密。我将代码分为两部分:加密和解密。但在解密过程中我会出错。有人能帮我解决这些问题吗 共享代码:Java 分别使用椭圆曲线密码对文本消息进行加密和解密,java,encryption,cryptography,elliptic-curve,Java,Encryption,Cryptography,Elliptic Curve,我有这段代码,它同时使用椭圆曲线密码对文本消息进行加密和解密。我将代码分为两部分:加密和解密。但在解密过程中我会出错。有人能帮我解决这些问题吗 共享代码: import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.Scanner; import java.security.InvalidAlgorithmParameterException; import java.securit
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Scanner;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Enumeration;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyAgreement;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
public class ENCRYPT {
public static byte[] iv = new SecureRandom().generateSeed(16);
public static void main(String[] args) {
System.out.println("IV :" + iv);
Scanner sc = new Scanner(System.in); // object for scanner
System.out.println("Enter your Message:");
String plainText = sc.nextLine();
System.out.println("Original plaintext message: " + plainText);
// Initialize two key pairs
KeyPair keyPairA = generateECKeys();
KeyPair keyPairB = generateECKeys();
// Create two AES secret keys to encrypt/decrypt the message
SecretKey secretKeyA = generateSharedSecret(keyPairA.getPrivate(),
keyPairB.getPublic());
SecretKey secretKeyB = generateSharedSecret(keyPairB.getPrivate(),
keyPairA.getPublic());
// Encrypt the message using 'secretKeyA'
String cipherText = encryptString(secretKeyA, plainText);
System.out.println("Encrypted cipher text: " + cipherText);
String encodedKeyA = Base64.getEncoder().encodeToString(secretKeyA.getEncoded());
String encodedKeyB = Base64.getEncoder().encodeToString(secretKeyB.getEncoded());
// Decrypt the message using 'secretKeyB'
String decryptedPlainText = decryptString(secretKeyB, cipherText);
System.out.println("Decrypted cipher text: " + decryptedPlainText);
System.out.println("Secret Key A: " + encodedKeyA);
System.out.println("Secret Key B: " + encodedKeyB);
}
public static KeyPair generateECKeys() {
try {
ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("brainpoolp256r1");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
"ECDH", "BC");
keyPairGenerator.initialize(parameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
return keyPair;
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException |
NoSuchProviderException e) {
e.printStackTrace();
return null;
}
}
public static SecretKey generateSharedSecret(PrivateKey privateKey,
PublicKey publicKey) {
try {
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "BC");
keyAgreement.init(privateKey);
keyAgreement.doPhase(publicKey, true);
SecretKey key = keyAgreement.generateSecret("AES");
return key;
} catch (InvalidKeyException | NoSuchAlgorithmException |
NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static String encryptString(SecretKey key, String plainText) {
try {
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] plainTextBytes = plainText.getBytes("UTF-8");
byte[] cipherText;
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipherText = new byte[cipher.getOutputSize(plainTextBytes.length)];
int encryptLength = cipher.update(plainTextBytes, 0,
plainTextBytes.length, cipherText, 0);
encryptLength += cipher.doFinal(cipherText, encryptLength);
return bytesToHex(cipherText);
} catch (NoSuchAlgorithmException | NoSuchProviderException |
NoSuchPaddingException | InvalidKeyException |
InvalidAlgorithmParameterException |
UnsupportedEncodingException | ShortBufferException |
IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
public static String decryptString(SecretKey key, String cipherText) {
try {
Key decryptionKey = new SecretKeySpec(key.getEncoded(),
key.getAlgorithm());
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] cipherTextBytes = hexToBytes(cipherText);
byte[] plainText;
cipher.init(Cipher.DECRYPT_MODE, decryptionKey, ivSpec);
plainText = new byte[cipher.getOutputSize(cipherTextBytes.length)];
int decryptLength = cipher.update(cipherTextBytes, 0,
cipherTextBytes.length, plainText, 0);
decryptLength += cipher.doFinal(plainText, decryptLength);
return new String(plainText, "UTF-8");
} catch (NoSuchAlgorithmException | NoSuchProviderException |
NoSuchPaddingException | InvalidKeyException |
InvalidAlgorithmParameterException |
IllegalBlockSizeException | BadPaddingException |
ShortBufferException | UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String bytesToHex(byte[] data, int length) {
String digits = "0123456789ABCDEF";
StringBuffer buffer = new StringBuffer();
for (int i = 0; i != length; i++) {
int v = data[i] & 0xff;
buffer.append(digits.charAt(v >> 4));
buffer.append(digits.charAt(v & 0xf));
}
return buffer.toString();
}
public static String bytesToHex(byte[] data) {
return bytesToHex(data, data.length);
}
public static byte[] hexToBytes(String string) {
int length = string.length();
byte[] data = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
data[i / 2] = (byte)((Character.digit(string.charAt(i), 16) << 4) + Character
.digit(string.charAt(i + 1), 16));
}
return data;
}
}
import java.io.UnsupportedEncodingException;
导入java.util.Base64;
导入java.util.Scanner;
导入java.security.invalidalgorithParameterException;
导入java.security.InvalidKeyException;
导入java.security.Key;
导入java.security.KeyPair;
导入java.security.KeyPairGenerator;
导入java.security.NoSuchAlgorithmException;
导入java.security.NoSuchProviderException;
导入java.security.PrivateKey;
导入java.security.PublicKey;
导入java.security.SecureRandom;
导入java.util.Enumeration;
导入javax.crypto.BadPaddingException;
导入javax.crypto.Cipher;
导入javax.crypto.IllegalBlockSizeException;
导入javax.crypto.KeyAgreement;
导入javax.crypto.NoSuchPaddingException;
导入javax.crypto.SecretKey;
导入javax.crypto.ShortBufferException;
导入javax.crypto.spec.IvParameterSpec;
导入javax.crypto.spec.SecretKeySpec;
导入org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
导入org.bouncycastle.jce.ECNamedCurveTable;
导入org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
公共类加密{
公共静态字节[]iv=新SecureRandom().generateSeed(16);
公共静态void main(字符串[]args){
System.out.println(“IV:+IV”);
Scanner sc=新扫描仪(System.in);//扫描仪的对象
System.out.println(“输入您的消息:”);
字符串明文=sc.nextLine();
System.out.println(“原始明文消息:“+明文”);
//初始化两个密钥对
KeyPair keyPairA=generateECKeys();
KeyPair keyPairB=generateECKeys();
//创建两个AES密钥以加密/解密消息
SecretKey secretKeyA=生成共享secret(keyPairA.getPrivate(),
keyPairB.getPublic());
SecretKey secretKeyB=生成共享secret(keyPairB.getPrivate(),
keyPairA.getPublic());
//使用“secretKeyA”加密邮件
字符串密文=加密字符串(secretKeyA,明文);
System.out.println(“加密密文:“+密文”);
字符串encodedKeyA=Base64.getEncoder().encodeToString(secretKeyA.getEncoded());
字符串encodedKeyB=Base64.getEncoder().encodeToString(secretKeyB.getEncoded());
//使用“secretKeyB”解密消息
字符串解密明文=解密字符串(secretKeyB,密文);
System.out.println(“解密密文:“+解密明文”);
System.out.println(“密钥A:+encodedKeyA”);
System.out.println(“密钥B:+encodedKeyB”);
}
公共静态密钥对生成器eckeys(){
试一试{
ECNamedCurveParameterSpec parameterSpec=ECNamedCurveTable.getParameterSpec(“brainpoolp256r1”);
KeyPairGenerator KeyPairGenerator=KeyPairGenerator.getInstance(
“ECDH”、“BC”);
keyPairGenerator.initialize(参数spec);
KeyPair KeyPair=keyPairGenerator.generateKeyPair();
返回键对;
}catch(NoSuchAlgorithmException | InvalidAlgorithmParameterException|
无此项(提供例外情况e){
e、 printStackTrace();
返回null;
}
}
公共静态保密密钥生成器共享保密密钥(PrivateKey PrivateKey,
公钥(公钥){
试一试{
KeyAgreement KeyAgreement=KeyAgreement.getInstance(“ECDH”、“BC”);
keyAgreement.init(私钥);
keyAgreement.doPhase(公钥,true);
SecretKey=keyagression.generateSecret(“AES”);
返回键;
}catch(InvalidKeyException | NoSuchAlgorithmException|
无此项(提供例外情况e){
//TODO自动生成的捕捉块
e、 printStackTrace();
返回null;
}
}
公共静态字符串encryptString(SecretKey密钥,字符串明文){
试一试{
IvParameterSpec ivSpec=新的IvParameterSpec(iv);
Cipher Cipher=Cipher.getInstance(“AES/GCM/NoPadding”,“BC”);
字节[]明文字节=明文.getBytes(“UTF-8”);
字节[]密文;
cipher.init(cipher.ENCRYPT_模式,密钥,ivSpec);
cipherText=新字节[cipher.getOutputSize(plainTextBytes.length)];
int encryptLength=cipher.update(明文字节,0,
明文字节数。长度,密文,0);
encryptLength+=cipher.doFinal(密文,encryptLength);
返回bytesToHex(密文);
}catch(NoSuchAlgorithmException | NoSuchProviderException|
NoSuchPaddingException | InvalidKeyException|
无效算法参数异常|
UnsupportedEncodingException | ShortBufferException|
IllegalBlockSizeException | BadPaddingException e){
e、 printStackTrace();
返回null;
}
}
公共静态字符串解密字符串(SecretKey密钥、字符串密文){
试一试{
Key decryptionKey=new SecretKeySpec(Key.getEncoded(),
key.getAlgorithm());
IvParameterSpec ivSpec=新的IvParameterSpec(iv);
Cipher Cipher=Cipher.getInstance(“AES/GCM/NoPadding”,“BC”);
字节[]密文字节=十六字节(密文);
字节[]明文;
cipher.init(cipher.DECRYPT_模式,decryptionKey,ivSpec);
明文=新字节[cipher.getOutputSize(cipherTextBytes.length)];
int decryptLength=cipher.update(cipherTextBytes,0,
cipherTextBytes.length,纯文本,0);
decryptLength+=cipher.doFinal(明文,decryptLength);
返回新字符串(纯文本,“UTF-8”);
}catch(NoSuchAlgorithmException | NoSuchProviderException|
NoSuchPaddingException | InvalidKeyException|
无效算法参数异常|
IllegalBlockSizeException | BadPaddingException|
ShortBufferException |不支持编码异常e){
e、 printStackTrace();
返回null;
}
}
公共静态字符串bytesToHex(字节[]数据,整数长度){
字符串数字=”
//Decrypt
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.util.Base64;
import java.util.Scanner;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
public class Decrypt {
public static byte[] iv = new SecureRandom().generateSeed(16);
public static void main(String[] args) {
/* Scanner scc = new Scanner(System.in);
System.out.println("Enter IV:");
String ivate = scc.nextLine();
byte[] iv = ivate.getBytes();
*/
System.out.println("IV=" + iv);
Scanner sc = new Scanner(System.in); // object for scanner
System.out.println("Enter your Cipher:");
String cipherText = sc.nextLine();
Scanner scanner = new Scanner(System.in); // object for scanner
System.out.println("Enter your Secret Key B:");
String encodedKeyB = scanner.nextLine();
byte[] decodedKeyB = Base64.getDecoder().decode(encodedKeyB);
SecretKey secretKeyB = new SecretKeySpec(decodedKeyB, 0, decodedKeyB.length, "AES");
// Initialize two key pairs
// KeyPair keyPairA = generateECKeys();
// KeyPair keyPairB = generateECKeys();
// Create two AES secret keys to encrypt/decrypt the message
//SecretKey secretKeyA = generateSharedSecret(keyPairA.getPrivate(),
// keyPairB.getPublic());
//SecretKey secretKeyB = generateSharedSecret(keyPairB.getPrivate(),
// keyPairA.getPublic());
// Encrypt the message using 'secretKeyA'
// String cipherText = encryptString(secretKeyA, plainText);
// System.out.println("Encrypted cipher text: " + cipherText);
// Decrypt the message using 'secretKeyB'
String decryptedPlainText = decryptString(secretKeyB, cipherText);
System.out.println("Decrypted cipher text: " + decryptedPlainText);
System.out.println(" cipher text: " + cipherText);
System.out.println("Key: " + secretKeyB);
}
/* public static KeyPair generateECKeys() {
try {
ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("brainpoolp256r1");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
"ECDH", "BC");
keyPairGenerator.initialize(parameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
return keyPair;
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
| NoSuchProviderException e) {
e.printStackTrace();
return null;
}
}
*/
/* public static SecretKey generateSharedSecret(PrivateKey privateKey,
PublicKey publicKey) {
try {
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "BC");
keyAgreement.init(privateKey);
keyAgreement.doPhase(publicKey, true);
SecretKey key = keyAgreement.generateSecret("AES");
return key;
} catch (InvalidKeyException | NoSuchAlgorithmException
| NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
*/
/* public static String encryptString(SecretKey secretkeyB, String plainText) {
try {
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] plainTextBytes = plainText.getBytes("UTF-8");
byte[] cipherText;
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipherText = new byte[cipher.getOutputSize(plainTextBytes.length)];
int encryptLength = cipher.update(plainTextBytes, 0,
plainTextBytes.length, cipherText, 0);
encryptLength += cipher.doFinal(cipherText, encryptLength);
return bytesToHex(cipherText);
} catch (NoSuchAlgorithmException | NoSuchProviderException
| NoSuchPaddingException | InvalidKeyException
| InvalidAlgorithmParameterException
| UnsupportedEncodingException | ShortBufferException
| IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
*/
public static String decryptString(SecretKey secretkeyB, String cipherText) {
try {
Key decryptionKey = new SecretKeySpec(secretkeyB.getEncoded(),
secretkeyB.getAlgorithm());
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] cipherTextBytes = hexToBytes(cipherText);
byte[] plainText;
cipher.init(Cipher.DECRYPT_MODE, decryptionKey, ivSpec);
plainText = new byte[cipher.getOutputSize(cipherTextBytes.length)];
int decryptLength = cipher.update(cipherTextBytes, 0,
cipherTextBytes.length, plainText, 0);
decryptLength = cipher.doFinal(plainText, decryptLength);
return new String(plainText, "UTF-8");
} catch (NoSuchAlgorithmException | NoSuchProviderException |
NoSuchPaddingException | InvalidKeyException |
InvalidAlgorithmParameterException |
IllegalBlockSizeException | BadPaddingException |
ShortBufferException | UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String bytesToHex(byte[] data, int length) {
String digits = "0123456789ABCDEF";
StringBuffer buffer = new StringBuffer();
for (int i = 0; i != length; i++) {
int v = data[i] & 0xff;
buffer.append(digits.charAt(v >> 4));
buffer.append(digits.charAt(v & 0xf));
}
return buffer.toString();
}
public static String bytesToHex(byte[] data) {
return bytesToHex(data, data.length);
}
public static byte[] hexToBytes(String string) {
int length = string.length();
byte[] data = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
data[i / 2] = (byte)((Character.digit(string.charAt(i), 16) << 4) + Character
.digit(string.charAt(i + 1), 16));
}
return data;
}
}