在android和go之间使用RSA

在一个用go和android的聊天项目中,我想使用RSA进行加密

我如何在 go 中创建私钥和公钥以发送到 android ?

我尝试了很多方法,但在 android 中当我想解析公钥 Android 时给出错误

  public static PublicKey stringToPublicKeytoserver(String publicKeyString)

    {

        try {

            publicKeyString = publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "");

            publicKeyString = publicKeyString.replace("-----END PUBLIC KEY-----", "");

            byte[] keyBytes = Base64.decode(publicKeyString, Base64.DEFAULT);

            X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);

            KeyFactory keyFactory = KeyFactory.getInstance(RSA);

            serveruk=keyFactory.generatePublic(spec);

            return serveruk;

        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {

            e.printStackTrace();

            return null;

        }

    }

安卓错误


java.security.spec.InvalidKeySpecException:com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException:解析公钥时出错


密钥生成


   // Generate RSA Keys

   miryanPrivateKey, err := rsa.GenerateKey(rand.Reader, 1024)

   fatal(err)



   // save PEM file

   pemfile, err := os.Create("public.pem")


   if err != nil {

       fmt.Println(err)

       os.Exit(1)

   }


   //publi := &miryanPrivateKey.PublicKey


   // http://golang.org/pkg/encoding/pem/#Block


   var pemkey = &pem.Block{

       Type : "PUBLIC KEY",

       Bytes : x509.MarshalPKCS1PublicKey(&miryanPrivateKey.PublicKey)}


   err = pem.Encode(pemfile, pemkey)


   if err != nil {

       fmt.Println(err)

       os.Exit(1)

   }


   pemfile.Close()

   //and even i use function to convert toPKCS8

   byt, _:= MarshalPKCS8PublicKey(&miryanPrivateKey.PublicKey)


   var pemkey = &pem.Block{

       Type : "PUBLIC KEY",

       Bytes : byt}


}

我认为我的主要问题是,去使用 pkcs1 但 android 使用 pkcs8


牧羊人nacy
浏览 128回答 1
1回答

紫衣仙女

我修复它 !我使用以下 Go 代码生成公钥和私钥:/* * Genarate rsa keys.*/package mainimport (    "crypto/rand"    "crypto/rsa"    "crypto/x509"    "encoding/gob"    "encoding/pem"    "fmt"    "os")func main() {    reader := rand.Reader    bitSize := 2048    key, err := rsa.GenerateKey(reader, bitSize)    checkError(err)    publicKey := key.PublicKey    saveGobKey("private.key", key)    savePEMKey("private.pem", key)    saveGobKey("public.key", publicKey)    savePublicPEMKey("public.pem", publicKey)}func saveGobKey(fileName string, key interface{}) {    outFile, err := os.Create(fileName)    checkError(err)    defer outFile.Close()    encoder := gob.NewEncoder(outFile)    err = encoder.Encode(key)    checkError(err)}func savePEMKey(fileName string, key *rsa.PrivateKey) {    outFile, err := os.Create(fileName)    checkError(err)    defer outFile.Close()    var privateKey = &pem.Block{        Type:  "PRIVATE KEY",        Bytes: x509.MarshalPKCS1PrivateKey(key),    }    err = pem.Encode(outFile, privateKey)    checkError(err)}func savePublicPEMKey(fileName string, pubkey rsa.PublicKey) {    asn1Bytes, err := x509.MarshalPKIXPublicKey(&pubkey)    checkError(err)    var pemkey = &pem.Block{        Type:  "PUBLIC KEY",        Bytes: asn1Bytes,    }    pemfile, err := os.Create(fileName)    checkError(err)    defer pemfile.Close()    err = pem.Encode(pemfile, pemkey)    checkError(err)}func checkError(err error) {    if err != nil {        fmt.Println("Fatal error ", err.Error())        os.Exit(1)    }}然后我用 GO 中生成的公钥在 android 中加密我的消息:static PublicKey serveruk;public final static String chi="RSA/ECB/OAEPPadding";public final static String RSA = "RSA";private final static int CRYPTO_BITS = 512;String pubPEM = "public key from public.pem";@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    stringToPublicKeytoserver(pubPEM);    Log.e("ENCODED", enc4golang("Please hide me !"));}public static PublicKey stringToPublicKeytoserver(String publicKeyString){    try {        publicKeyString = publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "");        publicKeyString = publicKeyString.replace("-----END PUBLIC KEY-----", "");        byte[] keyBytes = Base64.decode(publicKeyString, Base64.DEFAULT);        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);        KeyFactory keyFactory = KeyFactory.getInstance(RSA);        serveruk=keyFactory.generatePublic(spec);        return serveruk;    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {        e.printStackTrace();        return null;    }}private static byte[] enc4golang(String text, PublicKey pubRSA) throws Exception{    Cipher cipher = Cipher.getInstance(chi);    cipher.init(Cipher.ENCRYPT_MODE, pubRSA);    return cipher.doFinal(text.getBytes("UTF-8")); //i also advice you to use: .getBytes("UTF-8"); instead of data.getBytes();}public final static String enc4golang(String text){    try {        return Base64.encodeToString(enc4golang(text, serveruk) ,Base64.DEFAULT);  //send this string to golang    }    catch(Exception e)    {        e.printStackTrace();    }    return null;}然后我用这个 GO 代码解密它:package mainimport (    "crypto/rand"    "crypto/rsa"    "crypto/sha1"    "crypto/x509"    "encoding/base64"    "encoding/pem")func main(){    const priPEM = `private key from private.pem`    const pubPEM = `public key from public.pem`    base64DecodeBytes, err := base64.StdEncoding.DecodeString("encrypted data from android")    if err != nil {        panic(err)    }    privateKeyBlock, _ := pem.Decode([]byte(priPEM))    var pri *rsa.PrivateKey    pri, parseErr := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)    if parseErr != nil {        panic(parseErr)    }    decryptedData, decryptErr := rsa.DecryptOAEP(sha1.New(), rand.Reader, pri, base64DecodeBytes, nil)    if decryptErr != nil {        panic(decryptErr)    }    print(string(decryptedData))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go