英文:
casting a generic (interface) to a type when all possible types have same methods
问题
使用以下方法:
x509.CreateCertificate(rand.Reader, &template, &template, publicKey, privateKey)
从定义上看,这里的publicKey和privateKey都是类型为'any'的。在编译时,我不知道用户会提供哪种类型的密钥 - 这似乎是可以接受的,因为我可以传递任何一种。
然而,我在处理any
类型到这两种密钥类型之一时遇到了困难。
在我意识到可能有问题之前,我已经做到了这一点:
var privKey any
switch priv.(type) {
case *ecdsa.PrivateKey:
privKey = priv.(*ecdsa.PrivateKey)
case *rsa.PrivateKey:
privKey = priv.(*rsa.PrivateKey)
default:
return nil, nil, errors.New("no valid key type passed")
}
der, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, priv)
我可以将CreateCertificate
调用移到各个case内部,但这似乎是重复的代码。正确的做法是什么?
英文:
Take the method:
x509.CreateCertificate(rand.Reader, &template, &template, publicKey, privateKey)
looking at the defitiniton, both publicKey and privateKey here are type 'any'. I don't know at compile time which type of key a user will provide - and that seems fine as I can pass either in.
However, I am struggling with the handling of the any
to either of these types of keys.
This was where I got to before I realised I might have a problem:
var privKey any
switch priv.(type) {
case *ecdsa.PrivateKey:
privKey = priv.(*ecdsa.PrivateKey)
case *rsa.PrivateKey:
privKey = priv.(*rsa.PrivateKey)
default:
return nil, nil, errors.New("no valid key type passed")
}
der, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, priv)
I could move the CreateCertificate
call inside the cases, but that seems copypasta. Whats the correct way to do this?
答案1
得分: 2
正如评论中指出的那样,解决方案是私钥都遵循我忽略的crypto.Signer
接口。
因此可以执行priv.(crypto.Signer).Public()
。
英文:
As pointed out in the comments, the solution is that the private keys both adhere to the interface crypto.Signer
which I missed.
Therefore can do priv.(crypto.Signer).Public()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论