Как распечатать зашифрованные данные SealedObject без файлового ввода-вывода? - PullRequest
0 голосов
/ 21 декабря 2018

Ниже мой код.когда я пытаюсь распечатать запечатанный объект, он отображает только «javax.crypto.SealedObject@34dac684»

private void encryptUserCodes(List<UserCode> userCodes) {

        try {
            // generate a secret key using the DES algorithm
            key = KeyGenerator.getInstance("DES").generateKey();
            ecipher = Cipher.getInstance("DES");
            dcipher = Cipher.getInstance("DES");
            // initialize the ciphers with the given key
            ecipher.init(Cipher.ENCRYPT_MODE, key);
            dcipher.init(Cipher.DECRYPT_MODE, key);
            // create a sealed object
            SealedObject sealed = new SealedObject((Serializable) userCodes, ecipher);
            //PRINT SEALED OBJECT HERE
        }
        catch(Exception e){
            e.printStackTrace();
        }
}

Ответы [ 3 ]

0 голосов
/ 21 декабря 2018

Ваш sealed объект сериализуем.Таким образом, вы можете записать его в ObjectOutputStream:

try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
    out.writeObject(sealed);
    byte [] bytes =  bos.toByteArray();
    System.out.println(bytes);
} catch (IOException e) {
    e.printStackTrace();
}

Чтобы напечатать его более удобным для пользователя, вы можете закодировать его в base64:

String base64encoded = Base64.getEncoder().encodeToString(bytes);
System.out.println(base64encoded);
0 голосов
/ 21 декабря 2018

System.out.println всегда печатает значение метода toString().В вашем случае печать Class @ hex является реализацией по умолчанию в классе Object, которая наследуется во всех классах в java.

Вы можете создать собственный метод для печати вашего объекта.

Предоставьте определение метода с помощьюОбход желаемого результата путем вызова методов получения из вашего объекта и распечатки их.Конкатенация и возврат также возможны.

0 голосов
/ 21 декабря 2018

1.Шифрование:

Создание выходных потоков и использование Base64 Encoder для получения строки.

2.Расшифруйте:

Создайте новый шифр, входные потоки и используйте декодер Base 64, чтобы получить исходную строку.

Полностью рабочий пример (просто скопируйте и вставьте):

import javax.crypto.SecretKey;
import javax.crypto.KeyGenerator;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import java.io.Serializable;

import java.io.ByteArrayOutputStream;
import javax.crypto.CipherOutputStream;
import java.io.ObjectOutputStream;

import java.io.ByteArrayInputStream;
import javax.crypto.CipherInputStream;
import java.io.ObjectInputStream;

import java.util.Base64;

public class MyClass {
    public static void main(String args[]) {
        OtherClass myObject = new OtherClass();
        myObject.print();
    }
}

// you can add other public classes to this editor in any order
class OtherClass
{
public void print() {


 try {
       String userCodes = "Test123";
        // generate a secret key using the DES algorithm
        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
        Cipher ecipher = Cipher.getInstance("DES");
        // initialize the ciphers with the given key
        ecipher.init(Cipher.ENCRYPT_MODE, key);
        // create a sealed object
        SealedObject sealed = new SealedObject((Serializable) userCodes, ecipher);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(
            outputStream, ecipher);

    ObjectOutputStream oos = new ObjectOutputStream(cipherOutputStream);
    oos.writeObject( sealed );
    cipherOutputStream.close();

    byte[] values = outputStream.toByteArray();

    String base64encoded = Base64.getEncoder().encodeToString(values);
    System.out.println(base64encoded);

    // decrypt
    Cipher fcipher = Cipher.getInstance("DES");
    fcipher.init(Cipher.DECRYPT_MODE, key);

    ByteArrayInputStream istream = new ByteArrayInputStream(Base64.getDecoder().decode(base64encoded));
    CipherInputStream cipherInputStream = new CipherInputStream(istream, fcipher);
    ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
    SealedObject sealdedObject = (SealedObject) inputStream.readObject();
    System.out.println(sealdedObject.getObject(key));

}
catch(Exception e){
    e.printStackTrace();
}
}
}
...