This is a creation in Article, where the information may have evolved or changed.
Previously wrote the C # and Java language RSA algorithm interoperability program, and then find the Java and Go Language interoperability RSA algorithm, found that there is no ready, after exploration, the successful realization of the interoperability of the two, now share the following:
Note: 1. Both public and private keys cannot be mixed, that is, the Java public key cannot be used directly for go, and vice versa.
2. The following Java source decryption idea is:
(1) Copy the Java generated public key Pubkey_from_java to go
(2) Go uses Java's public key to encrypt a piece of information, Data,err=rsaencrypt ("Hello", Pubkey_from_java)
(3) Java uses its own private key Privkey_from_java decrypt this information data, has been verified through.
3. The idea of Go source decryption and the above-mentioned same, no longer repeat. Directly on the source code.
Java implementation of the RSA source code is as follows:
Package Rsa;import Java.security.Key; Import Java.security.KeyFactory; Import Java.security.KeyPair; Import Java.security.KeyPairGenerator; Import Java.security.PrivateKey; Import Java.security.PublicKey; Import Java.security.interfaces.RSAPrivateKey; Import Java.security.interfaces.RSAPublicKey; Import Java.security.spec.PKCS8EncodedKeySpec; Import Java.security.spec.X509EncodedKeySpec; Import Javax.crypto.Cipher; Import Sun.misc.BASE64Decoder; Import Sun.misc.BASE64Encoder; public class Rsahelper {/** * Private data member, primarily the key and private key * is generated by the program itself, and the public key is passed to the communication other party */private static string publickey;private static string privatekey;/** * Generate public and private keys */private static void Genkeys () throws exception{keypairgenerator Keypairgen = Keypairgenerator . getinstance ("RSA"); Number of key bits keypairgen.initialize (1024); Key pair KeyPair KeyPair = Keypairgen.generatekeypair (); Public key PublicKey PubKey = (rsapublickey) keypair.getpublic (); Private Privatekey Privkey = (rsaprivatekey) keypair.getprivate (); publickey= getkeystring (PubKey); privatekey= getkeystring (Privkey); }/** * Get program automatically generated public key * @return return public key */public static String Getpubkey () {return publickey;} /** * Get program automatically generated private key * @return return private key */public static String Getprivkey () {return privatekey;} /** * Get the public key * @param key key string (base64 encoded) * @throws Exception * * * static PublicKey Getpubli Ckey (String key) throws Exception {byte[] keybytes; Keybytes = (new Base64decoder ()). Decodebuffer (key); X509encodedkeyspec KeySpec = new X509encodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance ("RSA"); PublicKey PublicKey = Keyfactory.generatepublic (KeySpec); return publickey; }/** * Gets the private key * @param key key string (base64 encoded) * @throws Exception */public static Privatekey Getprivatekey (String key) throws Exception {Byte[] keybytes; Keybytes = (new Base64decoder ()). Decodebuffer (key); Pkcs8encodedkeyspec KeySpec = new Pkcs8encodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance ("RSA"); Privatekey Privatekey = keyfactory.generateprivate (KeySpec); return privatekey; }/** * Gets the key string (base64 encoded) * @return */public static string getkeystring (Key key) throws Excep tion {byte[] keybytes = key.getencoded (); String s = (new Base64encoder ()). Encode (keybytes); return s; }/** * Public key encryption generated using the Go language * @param pubkey_from_go the public key obtained from the server (Go language implementation) * @param plaintext the string to be encrypted * * Tatic string Encbygopubkey (string pubkey_from_go,string plaintext) throws Exception {//Add decryption class Cipher Cipher = C Ipher.getinstance ("RSA");//cipher.getinstance ("rsa/ecb/pkcs1padding"); byte[] plaintextbytes = Plaintext.getbytes (); Public key encryption publ generated by the Go languageIckey Pubkey_go=getpublickey (PUBKEY_FROM_GO); Cipher.init (Cipher.encrypt_mode, Pubkey_go); byte[] enbytes = cipher.dofinal (plaintextbytes); String encryptstring = (new Base64encoder ()). Encode (enbytes); return encryptstring; /** * Decrypt the go language with a private key the ciphertext generated by the Java public key * * * * * static string Decryptbyjavaprivkey (String privkey_from_java,s Tring encryptedstring) throws exception{//Add decryption class Cipher Cipher = Cipher.getinstance ("RSA");//cipher.getinstan CE ("rsa/ecb/pkcs1padding"); G0 the encrypted string byte[] enbytes= (New Base64decoder ()) from the public key generated by the Java language. Decodebuffer (encryptedstring); Get the key Privatekey by the key string Privatekey = Getprivatekey (Privkey_from_java); Decryption Cipher.init (Cipher.decrypt_mode, Privatekey); Byte[]debytes = Cipher.dofinal (enbytes); String Decryptstring=new string (debytes); return decryptstring; } public static void Main (string[] args) throws Exception {Genkeys (); String publickeystring =getpubkey (); System.out.println ("Public key:\n" + publickeystring); String privatekeystring = Getprivkey (); System.out.println ("Private key:\n" + privatekeystring); Java generated public and private key String pubkey_from_java= "Migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdmb2bxhcfeiosnxs0bd17isalelys2/0xk Qdju "+" VUYMDT+/5INM/S5UPDFRLIMS3I9ZJ3PTJWO7YZRFIBNODNLOFTQPNY6DI9FXNHDGJQMJHP1ZBHL7 "+" d74E63CBVTU6De Ocqfy/kcipjqnptzln89mm7ee3wbvlmvx3mo7ud2/geqidaqab "; String privkey_from_java= "Miibnwibadanbgkqhkig9w0baqefaascasewggedageaaogbaozvztefx96kiyfgz" + "RsPXuKxqV6XJLb/TE Pb0lrvtix237/kieb9lm6kmwuwiyzel3opc+0ly7vlnf+ige "+" gm2u59oo81jomj0veeeocnawmgnvlugxt3vgtrcifvnton6hyp/l8oki+ NCELPOWF "+" Z0YBT4TDZU+WA9FEY7U4PB+B5AGEAAOGBAL5MMBXGZWIDIB2HF0JFRFA0CHU9X7NR "+" mre8t9s08l4xrul4pbv1x1l mwmtid8h4ac9dxe858lfv0uoiqpdbxp9zmyoqbc97l "+" WDBOUTZT6OCXQ3HMVTOSZN9CFFIF6JXALZ8HGOCQAHTLVM4LWMYZNBGAYX/VJA9BX "+" Jvtuqdvxt9ageaageaageaageaagea "; Go-generated public and private keys String pubkey_from_go= "MIGFMA0GCSQGSIB3DQEBAQUAA4GNADCBIQKBGQDZSFV1QSCQYDY4VY+P4E3CATMV" + " PPXQCRVRF1CB4DRKV0HAU24Y7M5QYTT52KR539RDBKKDLAM6S20LWY7+5C0DGACD "+" wywd/7pecelyeipzjl07vro7ate8bfjya+wltgk9+ XNUIHIUMUKULW4KDX21+1NL "+" Auej6pew+dakmjwf6qidaqab "; String privkey_from_go= "miicxqibaakbgqdzsfv1qscqydy4vy+p4e3catmvppxqcrvrf1cb4drkv0hau24y" + "7m5qYtT52Kr539RdbKKd Lam6s20lwy7+5c0dgacdwywd/7pecelyeipzjl07vro7 "+" ate8bfjya+wltgk9+xnuihiumukulw4kdx21+1nlauej6pew+ Dakmjwf6qidaqab "+" Aogbajlnxentqj6ofcl9fmr2jlmjjtmrtqt9inqee7m3m7blhec+mcjohmnvbjam "+" ZpthDORdxIZ6oCuOf 6Z2+DL35LNTGFH5J7S34UP2BWZF1IYYQFYSCNEXGNHKT1G1 "+" xkqthmtc2gwwtheg+ S6CIIYW2IGRRP2RKE81VYHEXPREXF0HAKEA9IZB0MIYSMCB "+"/jemljb0lb3y/ B8xjgjqffbqt7bmwbvjvzwzvpnmnxi9swgdgupxscuairoxjz40 "+" irz2c9eOUWJBAOPJPVV8SGW4VASEOQLJVSQ/C/PIFX6RVZNDGLC8BRG7SGTPPJHG "+" 4g+m3mvgpcx1a/eu1mb+fhij2laz/ ptty6scqgaw9nwiwu3drivgcsmm0myh/3x9 "+" dacwlsjoctiodq1fq9rrede5qfpjnajdjfsijntx1f+l3yceebxtw0ynz2mcqbi8 "+ "9KP274IS5FKWKUFNKNUKUK4WKOUEXEO+LPR+VIHS7K6WQ8NGDD4/MUJOJBR5MKRW" + "Dpwqa3n5tmndqvgv8gmcqqcakgjgwygvo3/milffim Bp+m7/y3vcptarldxryqwo "+" aqjxwc71zgbfdityvdgjm1mtqc8xqek1fxn1vfpy2c6o "; The public key generated with the go language encrypts String plaintext = "hello,i am plaintext string! @sina. com"; String Encryptstring=encbygopubkey (Pubkey_from_go,plaintext); System.out.println ("Encrypted string: \ n" +encryptstring); Decrypts the G0 language string enstring_from_go= "jiyrvyv3kdisxn6fwmuzdjj/ljluv51ttnbbzi1m8h2jc/uzyxvnuyup66kd8d" from the Java public key encryption Eeroq0gaqwxdovbfauzodfputcbwz0ojzrnyoc1jle0/frtiq+goa7b97k2wdyueetkydnsahnzsabo+ma/hze+p+oizojozispavywyvd7xa= "; String Decryptstring=decryptbyjavaprivkey (PRIVKEY_FROM_JAVA,ENSTRING_FROM_GO); System.out.println ("decrypted string: \ n" +decryptstring); } }
Description
1. The above-mentioned Java code comments have been more complete, the children who have written the encryption should be able to read. Among the two packages introduced:
Import Sun.misc.BASE64Decoder;
Eclipse is not supported by default for BASE64 encoding, set method:
Right-click Project, Properties->java build Path->libraries->jre systemlibrary->access Rules, in the dialog box that appears, The first line resolution select Accessiable, the second line is filled with: * * (two asterisks).
Next comes the source of the Go language
Package Mainimport ("Crypto/rand" "Crypto/rsa" "crypto/x509" "Encoding/base64" "Encoding/pem" "Errors" "Flag" "FMT") var decrypted stringfunc init () {flag. Stringvar (&decrypted, "D", "", "encrypted data") flag. Parse ()}func main () {var data []byte var err error if decrypted! = "" {data, err = base64. Stdencoding.decodestring (decrypted) if err! = Nil {panic (err)}} else {//Use the public key from the client to add Secret valid information data, err = Rsaencrypt ([]byte ("polaris@studygolang.com"), Publickey_by_java) if err! = Nil { Panic (ERR)} FMT. PRINTLN ("RSA Encrypt (base64): \ n" + base64. Stdencoding.encodetostring (data)} data, Err = base64. Stdencoding.decodestring ("w/lt8krqlb7pj3sxi0sawcyfjvcnvr/tulgyhqux3l8dz5+ symjqtatsas3ks5qvmdmfbikg4tzia0wsqoqgt36z/ Xudrbvhxlifsowpo4xjcym4vbawnuiyezjded7jbswaphqtslinqclsxbh32tktj9dfmihd2/vp0bfyt/k= ") OrigData, err: = RsaDecrypt ( Data, Privatekey) if err! = Nil { Panic (ERR)} FMT. PRINTLN ("RSA Decrypt (base64): \ n" + string (origdata))}//Public and private keys can be read from a file var privatekey = []byte ('-----BEGIN RSA PRIVATE KEY-----miicxqibaakbgqdzsfv1qscqydy4vy+p4e3catmvppxqcrvrf1cb4drkv0hau24y7m5qytt52kr539rdbkkdlam6s20lwy7+ 5c0dgacdwywd/7pecelyeipzjl07vro7ate8bfjya+wltgk9+xnuihiumukulw4kdx21+1nlauej6pew+ dakmjwf6qidaqabaogbajlnxentqj6ofcl9fmr2jlmjjtmrtqt9inqee7m3m7blhec+mcjohmnvbjamzpthdordxiz6ocuof6z2+ dl35lntgfh5j7s34up2bwzf1iyyqfyscnexgnhkt1g1xkqthmtc2gwwtheg+s6ciiyw2igrrp2rke81vyhexprexf0hakea9izb0miysmcb/ jemljb0lb3y/b8xjgjqffbqt7bmwbvjvzwzvpnmnxi9swgdgupxscuairoxjz40irz2c9eouwjbaopjpvv8sgw4vaseoqljvsq/c/ pifx6rvzndglc8brg7sgtppjhg4g+m3mvgpcx1a/eu1mb+fhij2laz/ptty6scqgaw9nwiwu3drivgcsmm0myh/ 3x9dacwlsjoctiodq1fq9rrede5qfpjnajdjfsijntx1f+l3yceebxtw0ynz2mcqbi89kp274is5fkwkufnknukuk4wkouexeo+lpr+ vihs7k6wq8ngdd4/mujojbr5mkrwdpwqa3n5tmndqvgv8gmcqqcakgjgwygvo3/milffimbp+m7/ y3vcptarldxryqwoaqjxwc71zgbfdityvdgjm1mtqc8xqek1fxn1vfpy2c6o-----END RSA PRIVATE KEY-----')/**/varPrivatekey_by_java = []byte ('-----BEGIN RSA PRIVATE KEY-----miibnwibadanbgkqhkig9w0baqefaascasewggedageaaogbaozvztefx96kiyfgzrspxukxqv6xjlb/tepb0lrvtix237/ Kieb9lm6kmwuwiyzel3opc+0ly7vlnf+igegm2u59oo81jomj0veeeocnawmgnvlugxt3vgtrcifvnton6hyp/l8oki+ncelpowfz0ybt4tdzu +wa9fey7u4pb+ B5ageaaogbal5mmbxgzwidib2hf0jfrfa0chu9x7nrmre8t9s08l4xrul4pbv1x1lmwmtid8h4ac9dxe858lfv0uoiqpdbxp9zmyoqbc97lwdboutzt6ocxq3 Hmvtoszn9cffif6jxalz8hgocqahtlvm4lwmyznbgayx/vja9bxjvtuqdvxt9ageaageaageaageaagea-----END RSA PRIVATE KEY-----') var publickey = []byte ('-----BEGIN public KEY-----migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdzsfv1qscqydy4vy+ p4e3catmvppxqcrvrf1cb4drkv0hau24y7m5qytt52kr539rdbkkdlam6s20lwy7+5c0dgacdwywd/7pecelyeipzjl07vro7ate8bfjya+ Wltgk9+xnuihiumukulw4kdx21+1nlauej6pew+dakmjwf6qidaqab-----END Public KEY-----') var Publickey_by_java = []byte ('--- --begin Public KEY-----migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdmb2bxhcfeiosnxs0bd17isalelys2/0xkqdjuvuymdt+/5inm/ S5updfrlims3i9zj3ptjwo7yzrfibnodnloftqpny6di9fxnhdGjqmjhp1zbhl7d74e63cbvtu6deocqfy/kcipjqnptzln89mm7ee3wbvlmvx3mo7ud2/geqidaqab-----END Public KEY-----')// Use the public key (Java language generation) from the client to encrypt the Func rsaencrypt (Origdata []byte, PubKey []byte] ([]byte, error) {block, _: = Pem. Decode (pubkey) if block = = Nil {return nil, errors. New ("Public Key Error")} pubinterface, err: = X509. Parsepkixpublickey (block. Bytes) If err! = Nil {return nil, err} pub: = Pubinterface. (*rsa. PublicKey) return RSA. Encryptpkcs1v15 (Rand. Reader, Pub, Origdata)}//decrypt the information that is encrypted by the client (Java) using the server (Go language implementation, which is the program) public Key Cryptography Rsadecrypt (ciphertext []byte, Privkey []byte] ([] Byte, error) {block, _: = Pem. Decode (privkey) if block = = Nil {return nil, errors. New ("Private key error!") } priv, err: = X509. Parsepkcs1privatekey (block. Bytes) If err! = Nil {return nil, err} return RSA. Decryptpkcs1v15 (Rand. Reader, Priv, ciphertext)}
Description: For more information on the RSA encryption algorithm for Go language, please refer to: http://blog.studygolang.com/?p=137