This is a creation in Article, where the information may have evolved or changed.
Note: Here the Java code runs on Android, the final result, I look consistent
Requirements to be met by interoperability
- RSA Encryption BITS: Unified RSA 1024
- Group encryption Condition: rsa/ecb/pkcs1padding
The above conditions Java and go are to be satisfied, there is one point to note, although Java by default: Rsa/ecb/pkcs1padding. But Android is not, so the Android platform by default uses the RSA padding to be specified by itself. Go as long as decryption, Java as long as encryption. The private key and the public key platform have only one. The encryption results are turned into base64.
Java code:
/** *利用Go语言产生的公钥加密 * @param pubkey_from_go 从服务器(go语言实现)获取的公钥 * @param plainText 需要加密的字符串 */ public static String encByGoPubKey(String pubkey_from_go,String plainText) throws Exception { //加解密类 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); byte[] plainTextBytes = plainText.getBytes(); //用Go语言产生的公钥加密 PublicKey pubkey_go=getPublicKey(pubkey_from_go); cipher.init(Cipher.ENCRYPT_MODE, pubkey_go); byte[] enBytes = cipher.doFinal(plainTextBytes); String encryptString = Base64.encodeToString(enBytes,Base64.DEFAULT); // String encryptString = (new BASE64Encoder()).encode(enBytes); return encryptString; }
Go code:
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-----') func 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)}func Dersa (str string) (string) {var data []byte var err error data, err = base64. Stdencoding.decodestring (str) origdata, err: = Rsadecrypt (data, Privatekey) if err! = Nil {panic (err)} return string (Origdata)}
In the above code, it is important to ensure that the public and private keys are the same, even if the final result of the value of the IV is not the same, can also be solved.