Код: Выделить всё
static
{
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new BouncyCastlePQCProvider());
}
public static KeyPair generateKeyPair() {
try {
KeyPairGenerator kpg=KeyPairGenerator.getInstance("Kyber","BCPQC");
kpg.initialize(KyberParameterSpec.kyber1024);
return kpg.generateKeyPair();
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException(t.getMessage(), t);
}
}
public static byte[] encryptData(byte[] data, PublicKey publicKey)
{
Cipher cipher=null;
try
{
cipher=Cipher.getInstance("Kyber", "BCPQC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException(t.getMessage(), t);
}
}
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
{
Cipher cipher=null;
try
{
cipher=Cipher.getInstance("Kyber", "BCPQC");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException(t.getMessage(), t);
}
}
public static void main(String[] args) {
KeyPair keyPair=generateKeyPair();
byte[] publicKeyData=keyPair.getPublic().getEncoded();
byte[] privateKeyData=keyPair.getPrivate().getEncoded();
String publicKeyHex=Hex.toHexString(publicKeyData);
String privateKeyHex=Hex.toHexString(privateKeyData);
System.out.println("Public key length " + keyPair.getPublic().getEncoded().length + " format " + keyPair.getPublic().getFormat() + " algorithm " + keyPair.getPublic().getAlgorithm());
System.out.println("Public Key ");
System.out.println(publicKeyHex);
System.out.println("Private key length " + keyPair.getPrivate().getEncoded().length + " format " + keyPair.getPrivate().getFormat() + " algorithm " + keyPair.getPrivate().getAlgorithm());
System.out.println("Private Key ");
System.out.println(privateKeyHex);
String message="Hello World!";
byte[] encryptedData=encryptData(message.getBytes(), keyPair.getPublic());
String encryptedDataStr=DatatypeConverter.printBase64Binary(encryptedData);
System.out.println("encrypted:" + encryptedDataStr);
byte[] decryptedData=decryptData(encryptedData, keyPair.getPrivate());
String decrtyptedDataStr=new String(decryptedData);
System.out.println("decrypted:" + decrtyptedDataStr);
}
Код: Выделить всё
java.security.InvalidParameterException: Cipher only valid for wrapping/unwrappingПодробнее здесь: https://stackoverflow.com/questions/789 ... pting-data