如何在Java中为现有私钥添加密码

时间:2016-12-16 08:48:09

标签: java security encryption openssl rsa

假设我使用openssl创建了以前创建的私钥,但我决定不使用密码来保护它:

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

但后来我意识到我想保护它。

我知道如何使用openssl保护它,但我要求用Java来保护它。有可能吗?

1 个答案:

答案 0 :(得分:2)

首先从pem文件

加载并解压缩pkcs#1未加密密钥
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder

Builder.load_string('''
<SubWidget1>:
    Label:
        text: 'number is bigger than 3'
    Button:
        text: 'click here to decrease'
        on_press: root.parent.number -= 1

<SubWidget2>:
    Label:
        text: 'number is smaller than 3'
    Button:
        text: 'click here to increase'
        on_press: root.parent.number += 1

<MyWidget>
    number: 0
''')

class SubWidget1(BoxLayout):
    pass

class SubWidget2(BoxLayout):
    pass

class MyWidget(BoxLayout):
    number = NumericProperty()

    def __init__(self, *args):
        super(MyWidget, self).__init__(*args)
        self.widget = None
        self._create_widget()

    def _create_widget(self):
        print(self.number)
        if self.widget is not None:
            self.remove_widget(self.widget)
        if self.number > 3:
            self.widget = SubWidget1()
        else:
            self.widget = SubWidget2()
        self.add_widget(self.widget)

    def on_number(self, obj, value):
        self._create_widget()

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

然后使用this code的第二部分加密密钥(我已经包含了它)

String pem = new String(Files.readAllBytes(Paths.get("rsa.key")));
String privateKeyPEM = pem.replace(
        "-----BEGIN RSA PRIVATE KEY-----\n", "")
             .replace("-----END RSA PRIVATE KEY-----", "");
 byte[] encodedPrivateKey = Base64.getDecoder().decode(privateKeyPEM);

使用以下代码进行解密(从here中删除)

 // We must use a PasswordBasedEncryption algorithm in order to encrypt the private key, you may use any common algorithm supported by openssl, you can check them in the openssl documentation http://www.openssl.org/docs/apps/pkcs8.html
String MYPBEALG = "PBEWithSHA1AndDESede";
String password = "pleaseChangeit!";

int count = 20;// hash iteration count
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);

// Create PBE parameter set
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

Cipher pbeCipher = Cipher.getInstance(MYPBEALG);

// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

// Encrypt the encoded Private Key with the PBE key
byte[] ciphertext = pbeCipher.doFinal(encodedPrivateKey);

// Now construct  PKCS #8 EncryptedPrivateKeyInfo object
AlgorithmParameters algparms = AlgorithmParameters.getInstance(MYPBEALG);
algparms.init(pbeParamSpec);
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(algparms, ciphertext);

// and here we have it! a DER encoded PKCS#8 encrypted key!
byte[] encryptedPkcs8 = encinfo.getEncoded();
相关问题