发送私钥和公钥?

时间:2009-05-19 11:11:27

标签: c# bouncycastle

我需要以字符串格式传递公钥和私钥,以便在pgp中进行加密和解密。我已经生成了这样的键,但我无法使用它们。所以任何人都可以告诉我如何从字符串格式获取公钥和私钥。并且rsakeygenerator还没有为私钥提供密码。那么我在哪里获得私钥的密码呢?

private void button2_Click(object sender, EventArgs e)
{
    // keyPair = createASymRandomCipher();
    //CipherPublicKey publicKey = getCipherPublicKey(keyPair);
    AsymmetricCipherKeyPair keyPair = createASymRandomCipher();
    Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters pubkey = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)keyPair.Public;
    Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters privkey = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)keyPair.Private;
    CipherPublicKey pbkey = getCipherPublicKey(pubkey);
    CipherPrivateKey prvkey = getCipherPrivateKey(privkey);

}

private static AsymmetricCipherKeyPair createASymRandomCipher() 
{
    RsaKeyPairGenerator r = new RsaKeyPairGenerator();
    r.Init(new KeyGenerationParameters(new SecureRandom(),
          1024));
    AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
    return keys;
}

[Serializable]
private struct CipherPrivateKey
{
    public byte[] modulus; 
    public byte[] publicExponent; 
    public byte[] privateExponent; 
    public byte[] p; 
    public byte[] q; 
    public byte[] dP; 
    public byte[] dQ; 
    public byte[] qInv;
}

[Serializable]
private struct CipherPublicKey 
{ 
    public bool isPrivate; 
    public byte[] modulus; 
    public byte[] exponent;
}

private static CipherPublicKey getCipherPublicKey(Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters cPublic) 
{ 
    CipherPublicKey cpub = new CipherPublicKey(); cpub.modulus = cPublic.Modulus.ToByteArray(); 
    cpub.exponent = cPublic.Exponent.ToByteArray(); 
    return cpub; 
}

private static CipherPrivateKey getCipherPrivateKey(Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters cPrivate)
{
    CipherPrivateKey cpri = new CipherPrivateKey(); 
    cpri.dP = cPrivate.DP.ToByteArray(); 
    cpri.dQ = cPrivate.DQ.ToByteArray(); 
    cpri.modulus = cPrivate.Modulus.ToByteArray(); 
    cpri.p = cPrivate.P.ToByteArray(); 
    cpri.privateExponent = cPrivate.Exponent.ToByteArray(); 
    cpri.publicExponent = cPrivate.PublicExponent.ToByteArray(); 
    cpri.q = cPrivate.Q.ToByteArray(); 
    cpri.qInv = cPrivate.QInv.ToByteArray(); 
    return cpri;
}

2 个答案:

答案 0 :(得分:0)

您需要询问用户密码。 拥有密码短语的重点在于,如果没有密码,您将无法计算私钥,只有用户才能提供密钥。

(我没有看过你的其余代码,不熟悉BouncyCastle API。我确实怀疑具有大量字节数组的可变结构的智慧......)

答案 1 :(得分:0)

转换问题的答案是将它们转换为Base64Strings

如果你想要它是十六进制的(这样用户可以更容易地输入它),你可以使用System.Runtime.Remoting.Metadata.W3cXsd2001命名空间来转换为HEX代表/从HEX代表转换。这是一个example in C#

我还会说你的过程中可能存在安全漏洞,但我不确定我是否有资格解决它。 (见Jon的帖子)