How to store AES 256 Key in PKCS12 Keystore (.pks

2020-05-05 01:14发布

问题:

I need to store AES 256 bit key in a keystore using C#. I tried to using Org.BouncyCastle.Pkcs.Pkcs12Store but not able to store AES Key. I can do it in JAVA using the following code but not able to the same in C#.

try{
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(null, null);

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        Key key = keyGen.generateKey();
        for(byte b: key.getEncoded()) {
            System.out.print(b);
        }
        System.out.println("");
        keyStore.setKeyEntry("secret", key, "password".toCharArray(), null);

        keyStore.store(new FileOutputStream("output.p12"), "password".toCharArray());

        try{
            keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(new FileInputStream("output.p12"), "password".toCharArray());

            Key pvtKey = keyStore.getKey("secret", "password".toCharArray());
            //System.out.println(pvtKey.getEncoded().toString());
            for(byte b: pvtKey.getEncoded()) {
                System.out.print(b);
            }
            System.out.println("");
        } catch (Exception ex){
            ex.printStackTrace();
        }
    } catch (Exception ex){
        ex.printStackTrace();
    }

Please help me out.

标签: aes .net pkcs#12