How to store AES 256 Key in PKCS12 Keystore (.pks file or .p12) in C#

徘徊边缘 提交于 2019-12-04 06:42:35

问题


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.

来源:https://stackoverflow.com/questions/58622155/how-to-store-aes-256-key-in-pkcs12-keystore-pks-file-or-p12-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!