我试图在iOS和C#之间设置RSA加密通道。
在iOS中,公共密钥是使用安全框架生成的。
代码段
:noautocmd
结果:CursorMoved
在C#中,我试图使用上面生成的公共密钥来加密数据。
C#代码段:
NSData* tag = [@"com.x.x.x" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* attributes =
@{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeRSA,
(id)kSecAttrKeySizeInBits: @1024,
(id)kSecPrivateKeyAttrs:
@{ (id)kSecAttrIsPermanent: @YES,
(id)kSecAttrApplicationTag: tag,
},
};
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes,
&error);
if (!privateKey) {
NSError *err = CFBridgingRelease(error);
// Handle the error. . .
}
SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
我正在评估"MIGJAoGBAMIt95f4xaP7vYV/+Hdyb4DK0oKvw495PrRYG3nsYgVP7zlBE/rTN6Nmt69W9d0nGefuRlJFIr9TA8vlJmqTus6uXEasBuEjzH7vM7HQeAK6i8qEbVy0T+Uuq+16yy059NL7i/VWljVE6rqTntDUELmbIwNBwj6oBuL1z3SnFoMjAgMBAAE="
,并手动复制const string pKey = "MIGJAoGBAMIt95f4xaP7vYV/+Hdyb4DK0oKvw495PrRYG3nsYgVP7zlBE/rTN6Nmt69W9d0nGefuRlJFIr9TA8vlJmqTus6uXEasBuEjzH7vM7HQeAK6i8qEbVy0T+Uuq+16yy059NL7i/VWljVE6rqTntDUELmbIwNBwj6oBuL1z3SnFoMjAgMBAAE=";
byte[] publicKeyBytes = Convert.FromBase64String(pKey);
var stream = new MemoryStream(publicKeyBytes);
Asn1Object asn1Object = Asn1Object.FromStream(stream);
和asn1Object
,在这种情况下是
Modulus
然后我可以使用生成
Exponent
Q1。有没有办法遍历ans1Object并获取相应的数据?
Q2。有什么方法可以在C#中直接使用iOS生成的Base64(公钥)?
Q3。我需要将相同格式的公钥发送回客户端。
P.S。任何指导和帮助将不胜感激。
答案 0 :(得分:0)
所以如此,
经过大量研究和数百个堆栈溢出选项卡。
我可以使用C#中的iOS生成的公钥来使用Bouncy Castle进行加密。
pkey : Public Key given from client
下面的代码段
const string pKey = "MIGJAoGBAMIt95f4xaP7vYV/+Hdyb4DK0oKvw495PrRYG3nsYgVP7zlBE/rTN6Nmt69W9d0nGefuRlJFIr9TA8vlJmqTus6uXEasBuEjzH7vM7HQeAK6i8qEbVy0T+Uuq+16yy059NL7i/VWljVE6rqTntDUELmbIwNBwj6oBuL1z3SnFoMjAgMBAAE=";
byte[] publicKeyBytes = Convert.FromBase64String(pKey);
var stream = new MemoryStream(publicKeyBytes);
Asn1Object asn1Object = Asn1Object.FromStream(stream);
Asn1Encodable asn1Sequence = asn1Object;
AlgorithmIdentifier algorithmIdentifier = new
AlgorithmIdentifier(PkcsObjectIdentifiers.IdRsaesOaep);
SubjectPublicKeyInfo subjectPublicKeyInfo = new
SubjectPublicKeyInfo(algorithmIdentifier, asn1Sequence);
AsymmetricKeyParameter asymmetricKeyParameter2 =
PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
RsaKeyParameters rsaKeyParameters =
(RsaKeyParameters)asymmetricKeyParameter2;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
string test = "John snow is the true king";
byte[] encbyte = rsa.Encrypt(Encoding.UTF8.GetBytes(test), RSAEncryptionPadding.Pkcs1);
string encrt = Convert.ToBase64String(encbyte);
P.S。到目前为止,代码还不是很优化,所以请忽略它。