e205. signing a java object.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 47 行

TXT
47
字号
A signed object makes a copy of a serializable object and signs it with a private key. Since the signed object makes a copy of the original object, any further modifications to the original object do not affect the signed object. 
    // Create a public and private key
    PublicKey publicKey = null;
    PrivateKey privateKey = null;
    try {
        // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024);
        KeyPair keypair = keyGen.genKeyPair();
        privateKey = keypair.getPrivate();
        publicKey = keypair.getPublic();
    } catch (NoSuchAlgorithmException e) {
    }
    
    // Create the signed object
    SignedObject so = null;
    try {
        Serializable o = new MyClass();
        Signature sig = Signature.getInstance(privateKey.getAlgorithm());
        so = new SignedObject(o, privateKey, sig);
    } catch (NoSuchAlgorithmException e) {
    } catch (SignatureException e) {
    } catch (InvalidKeyException e) {
    } catch (IOException e) {
    }
    
    // Verify the signed object
    try {
        Signature sig = Signature.getInstance(publicKey.getAlgorithm());
        // Verify the signed object
        boolean b = so.verify(publicKey, sig);
    
        // Retrieve the object
        MyClass o = (MyClass)so.getObject();
    } catch (SignatureException e) {
    } catch (InvalidKeyException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (ClassNotFoundException e) {
    } catch (IOException e) {
    }
    
    public class MyClass implements Serializable {
        String s = "my string";
        int i = 123;
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?