├── .gitignore ├── example ├── JavaScript.md ├── .Net.md └── JAVA.md ├── example_test.go ├── gorsaSign.go ├── gorsa.go ├── rsakey.go ├── README.md ├── rsa.go ├── rsa_ext.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | 16 | .idea -------------------------------------------------------------------------------- /example/JavaScript.md: -------------------------------------------------------------------------------- 1 | # 对应 js 版本 2 | 3 | ```js 4 | var NodeRSA = require('node-rsa'); 5 | 6 | const encrypt_rsa = function (data) { 7 | 8 | const privateKey = new NodeRSA("-----BEGIN PRIVATE KEY-----\n" + 9 | 10 | "客户生成私钥\n" + 11 | 12 | "-----END PRIVATE KEY-----"); 13 | 14 | const result = privateKey.encryptPrivate(data, "base64"); 15 | 16 | const hexResult = Buffer.from(result, 'utf8').toString('hex'); 17 | 18 | return hexResult; 19 | 20 | } 21 | ``` 22 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Keep in sync with ../base32/example_test.go. 6 | 7 | package gorsa 8 | 9 | import ( 10 | "fmt" 11 | "testing" 12 | ) 13 | 14 | func Test_Example(t *testing.T) { 15 | res, err := GenerateKey(1024) 16 | if err != nil { 17 | fmt.Println(err) 18 | return 19 | } 20 | publicKey := res.PublicKeyBase64 21 | privateKey := res.PrivateKeyBase64 22 | 23 | fmt.Println("\n私钥: \n\r" + privateKey) 24 | fmt.Println("\n公钥: \n\r" + publicKey) 25 | fmt.Println("\n私钥加密 —— 公钥解密") 26 | 27 | str := `{"domainId":"id", "externalUserId":"test001"}` 28 | fmt.Println("\n\r明文:\r\n" + str) 29 | encodedData, err := PriKeyEncrypt(str, privateKey) 30 | if err != nil { 31 | fmt.Println(err) 32 | return 33 | } 34 | fmt.Println("\n密文:\r\n" + encodedData) 35 | 36 | decodedData, err := PublicDecrypt(encodedData, publicKey) 37 | if err != nil { 38 | fmt.Println(err) 39 | return 40 | } 41 | fmt.Println("\n解密后文字: \r\n" + decodedData) 42 | } 43 | -------------------------------------------------------------------------------- /gorsaSign.go: -------------------------------------------------------------------------------- 1 | package gorsa 2 | 3 | // 使用RSAWithMD5算法签名 4 | func SignMd5WithRsa(data string, privateKey string) (string, error) { 5 | grsa := RSASecurity{} 6 | grsa.SetPrivateKey(privateKey) 7 | 8 | sign, err := grsa.SignMd5WithRsa(data) 9 | if err != nil { 10 | return "", err 11 | } 12 | 13 | return sign, err 14 | } 15 | 16 | // 使用RSAWithSHA1算法签名 17 | func SignSha1WithRsa(data string, privateKey string) (string, error) { 18 | grsa := RSASecurity{} 19 | grsa.SetPrivateKey(privateKey) 20 | 21 | sign, err := grsa.SignSha1WithRsa(data) 22 | if err != nil { 23 | return "", err 24 | } 25 | 26 | return sign, err 27 | } 28 | 29 | // 使用RSAWithSHA256算法签名 30 | func SignSha256WithRsa(data string, privateKey string) (string, error) { 31 | grsa := RSASecurity{} 32 | grsa.SetPrivateKey(privateKey) 33 | 34 | sign, err := grsa.SignSha256WithRsa(data) 35 | if err != nil { 36 | return "", err 37 | } 38 | return sign, err 39 | } 40 | 41 | // 使用RSAWithMD5验证签名 42 | func VerifySignMd5WithRsa(data string, signData string, publicKey string) error { 43 | grsa := RSASecurity{} 44 | grsa.SetPublicKey(publicKey) 45 | return grsa.VerifySignMd5WithRsa(data, signData) 46 | } 47 | 48 | // 使用RSAWithSHA1验证签名 49 | func VerifySignSha1WithRsa(data string, signData string, publicKey string) error { 50 | grsa := RSASecurity{} 51 | grsa.SetPublicKey(publicKey) 52 | return grsa.VerifySignSha1WithRsa(data, signData) 53 | } 54 | 55 | // 使用RSAWithSHA256验证签名 56 | func VerifySignSha256WithRsa(data string, signData string, publicKey string) error { 57 | grsa := RSASecurity{} 58 | grsa.SetPublicKey(publicKey) 59 | return grsa.VerifySignSha256WithRsa(data, signData) 60 | } 61 | -------------------------------------------------------------------------------- /gorsa.go: -------------------------------------------------------------------------------- 1 | package gorsa 2 | 3 | import ( 4 | "encoding/base64" 5 | "encoding/hex" 6 | ) 7 | 8 | // PublicEncrypt 公钥加密 9 | func PublicEncrypt(data, publicKey string) (string, error) { 10 | 11 | gRsa := RSASecurity{} 12 | gRsa.SetPublicKey(publicKey) 13 | 14 | rsaData, err := gRsa.PubKeyENCTYPT([]byte(data)) 15 | if err != nil { 16 | return "", err 17 | } 18 | 19 | baseData := base64.StdEncoding.EncodeToString(rsaData) 20 | return hex.EncodeToString([]byte(baseData)), nil 21 | } 22 | 23 | // PriKeyEncrypt 私钥加密 24 | func PriKeyEncrypt(data, privateKey string) (string, error) { 25 | 26 | gRsa := RSASecurity{} 27 | gRsa.SetPrivateKey(privateKey) 28 | 29 | rsaData, err := gRsa.PriKeyENCTYPT([]byte(data)) 30 | if err != nil { 31 | return "", err 32 | } 33 | 34 | baseData := base64.StdEncoding.EncodeToString(rsaData) 35 | return hex.EncodeToString([]byte(baseData)), nil 36 | } 37 | 38 | // PublicDecrypt 公钥解密 39 | func PublicDecrypt(data, publicKey string) (string, error) { 40 | dataByte, err := hex.DecodeString(data) 41 | if err != nil { 42 | return "", err 43 | } 44 | 45 | dataBs, err := base64.StdEncoding.DecodeString(string(dataByte)) 46 | if err != nil { 47 | return "", err 48 | } 49 | 50 | gRsa := RSASecurity{} 51 | if err := gRsa.SetPublicKey(publicKey); err != nil { 52 | return "", err 53 | } 54 | 55 | rsaData, err := gRsa.PubKeyDECRYPT(dataBs) 56 | if err != nil { 57 | return "", err 58 | } 59 | 60 | return string(rsaData), nil 61 | } 62 | 63 | // PriKeyDecrypt 私钥解密 64 | func PriKeyDecrypt(data, privateKey string) (string, error) { 65 | dataByte, err := hex.DecodeString(data) 66 | if err != nil { 67 | return "", err 68 | } 69 | 70 | dataBs, _ := base64.StdEncoding.DecodeString(string(dataByte)) 71 | 72 | gRsa := RSASecurity{} 73 | 74 | if err := gRsa.SetPrivateKey(privateKey); err != nil { 75 | return "", err 76 | } 77 | 78 | rsaData, err := gRsa.PriKeyDECRYPT(dataBs) 79 | if err != nil { 80 | return "", err 81 | } 82 | 83 | return string(rsaData), nil 84 | } 85 | -------------------------------------------------------------------------------- /rsakey.go: -------------------------------------------------------------------------------- 1 | package gorsa 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/rsa" 6 | "crypto/x509" 7 | "encoding/base64" 8 | "encoding/pem" 9 | "fmt" 10 | ) 11 | 12 | type RSAKey struct { 13 | PublicKeyPem []byte //公钥pem字符串 14 | PrivateKeyPem []byte //私钥pem字符串 15 | 16 | PublicKeyBase64 string //公钥base64字符串 17 | PrivateKeyBase64 string //私钥base64字符串 18 | 19 | PublicKey *rsa.PublicKey //公钥 20 | PrivateKey *rsa.PrivateKey //私钥 21 | } 22 | 23 | // GenerateKey 生成RSA私钥和公钥 24 | // bits 证书大小 25 | func GenerateKey(bits int) (resp RSAKey, err error) { 26 | // -------------------------- 设置私钥 -------------------------- 27 | // GenerateKey 函数使用随机数据生成器,random 生成一对具有指定字位数的RSA密钥 28 | privateKey, err := rsa.GenerateKey(rand.Reader, bits) // Reader 是一个全局、共享的密码用强随机数生成器 29 | if err != nil { 30 | return 31 | } 32 | // 通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串 33 | X509PrivateKey, _ := x509.MarshalPKCS8PrivateKey(privateKey) 34 | // 对x509私钥,进行pem格式编码 35 | privateKeyPem := pem.EncodeToMemory(&pem.Block{ 36 | Type: "Private key", 37 | Bytes: X509PrivateKey, 38 | }) 39 | // 对x509私钥,进行base64格式编码 40 | privateKeyBase64 := fmt.Sprintf( 41 | "-----BEGIN Private key-----\n%s\n-----END Private key-----", 42 | base64.StdEncoding.EncodeToString(X509PrivateKey), 43 | ) 44 | resp.PrivateKeyBase64 = privateKeyBase64 45 | resp.PrivateKeyPem = privateKeyPem 46 | resp.PrivateKey = privateKey 47 | 48 | // -------------------------- 设置公钥 -------------------------- 49 | // 获取公钥的数据 50 | publicKey := &privateKey.PublicKey 51 | // X509对公钥编码 52 | X509PublicKey, err := x509.MarshalPKIXPublicKey(publicKey) 53 | if err != nil { 54 | return 55 | } 56 | // 对x509公钥,进行pem格式编码 57 | publicKeyPem := pem.EncodeToMemory(&pem.Block{ 58 | Type: "Public key", 59 | Bytes: X509PublicKey, 60 | }) 61 | // 对x509公钥,进行base64格式编码 62 | publicKeyBase64 := fmt.Sprintf("-----BEGIN Public key-----\n%s\n-----END Public key-----", 63 | base64.StdEncoding.EncodeToString(X509PublicKey), 64 | ) 65 | resp.PublicKeyBase64 = publicKeyBase64 66 | resp.PublicKeyPem = publicKeyPem 67 | resp.PublicKey = publicKey 68 | return 69 | } 70 | -------------------------------------------------------------------------------- /example/.Net.md: -------------------------------------------------------------------------------- 1 | # 对应.Net版本 2 | 3 | 1、需要先引入 [BouncyCastle.Crypto](https://www.nuget.org/packages/BouncyCastle.Crypto.dll/) 4 | 5 | ```c# 6 | using System; 7 | 8 | using Org.BouncyCastle.Crypto; 9 | 10 | using Org.BouncyCastle.Security; 11 | 12 | using System.Security.Cryptography; 13 | 14 | using System.Text; 15 | 16 | using System.IO; 17 | 18 | using Org.BouncyCastle.OpenSsl; 19 | 20 | using Org.BouncyCastle.Crypto.Parameters; 21 | 22 | 23 | 24 | namespace SSOEncrypt 25 | 26 | { 27 | 28 | 29 | 30 | public class RSAEncrypt 31 | 32 | { 33 | 34 | public static string RSAEncryptByPrivateKey(string privateKey, string strEncryptString) 35 | 36 | { 37 | 38 | //加载私钥 39 | 40 | RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider(); 41 | 42 | var byteArray = Encoding.ASCII.GetBytes(privateKey); 43 | 44 | using (var ms = new MemoryStream(byteArray)) 45 | 46 | { 47 | 48 | using (var sr = new StreamReader(ms)) 49 | 50 | { 51 | 52 | var pr = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(sr); 53 | 54 | var rsaParams = pr.ReadPemObject(); 55 | 56 | var pk = PrivateKeyFactory.CreateKey(rsaParams.Content); 57 | 58 | privateRsa.ImportParameters(DotNetUtilities.ToRSAParameters(pk as RsaPrivateCrtKeyParameters)); 59 | 60 | pr.Reader.Close(); 61 | 62 | } 63 | 64 | } 65 | 66 | 67 | 68 | //转换密钥 69 | 70 | AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa); 71 | 72 | IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致 73 | 74 | c.Init(true, keyPair.Private); //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 75 | 76 | 77 | 78 | byte[] DataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString); 79 | 80 | byte[] outBytes = c.DoFinal(DataToEncrypt);//加密 81 | 82 | string strBase64 = Convert.ToBase64String(outBytes); 83 | 84 | byte[] byteArr = Encoding.UTF8.GetBytes(strBase64); 85 | 86 | StringBuilder sb = new StringBuilder(byteArr.Length * 2); 87 | 88 | foreach (byte b in byteArr) 89 | 90 | { 91 | 92 | sb.AppendFormat("{0:x2}", b); 93 | 94 | } 95 | 96 | return sb.ToString(); 97 | 98 | } 99 | 100 | static void Main() 101 | 102 | { 103 | 104 | string data = "{"domainId":"demo","externalUserId":"hello1@sso.com"}"; 105 | 106 | string pem = "-----BEGIN PRIVATE KEY-----n" + 107 | 108 | // 私钥文本 109 | 110 | "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAK8mzOMZtCxA6md7pYz4pzZv69FrdILu5fd8M9SMGMKPP3lzsFMquaBHQ5fF1wkV/6U/EkAjELLwq4pwQB1S+vXp3jP4OtR8aA+gO7tYrodQswoJKfm49fDEYJ8d0VKIRqM4DeG9ihky2EIAzh5HJJsuqdLSMVllwVoDUaPBMBxBAgMBAAECgYBGMS569JoYAgvuXMcDr8KTNlczHfUbY9IVVFkRHPPvRKkTayGGsuChMu4LrOV4ZrCE8LnHqkXO8FROrp2DIvYfXMWjw2kXmIragHCxYCynz3XHsvig0YtFaDuS6xGjAGEwcYjyGVyRphgOzfYjwueqx6j81XL+8ejjx/aAlxyqAQJBAOXwTltxVlPg9UV3cF/QHJ0/+0sFUF5lrZxWdqDF/FfgeMY7SkfFX7qSmp5O4myz5ry9ZEWE3Xfvc1IwSyeDBSkCQQDDANcZMRh1s5kxGH2mJ2dixCmPRot3m/gbobczT6nqzWZh+srnFSr6oj5KWpFOb/KZf9fpi+y27OdiqaUyielZAkBURmMxuLR/QbAjqccSFuCl8dFUiboPHw0mg7ou6uG2A5vAa/Kpo3mWlCz/YMI0PSuQeYnKwQu67ZRCx1iEPs0hAkAvBLLYlifpqWZUmi0htPqOq/HBZCcYrfjC4NlFe/3iaag4E7p8wXPdfuU6FGBY41FBhbvPyjdHXBPmjDUS3IHxAkEAhKOLVD4jdR1RhXAL19MMNdpn5Qa4X4fxOH1ZXYPhsr2hfM2YFKv5LehNCPy92dXoqgcqSx75II0uqED2xNsrXw==n" + 111 | 112 | "-----END PRIVATE KEY-----"; 113 | 114 | string encryptData = RSAEncryptByPrivateKey(pem, data); 115 | 116 | Console.WriteLine(encryptData); 117 | 118 | } 119 | 120 | } 121 | 122 | } 123 | ``` 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GoRSA Encryption library 2 | 3 | based on https://github.com/farmerx/gorsa Optimized the following points for packaging: 4 | 5 | - Optimization of public and private keys requires registration and initialization in advance. 6 | - The encryption machine does not perform base64 processing, and avoids secondary encapsulation of base64 during cross-program transfer or storage 7 | - The incoming return uses the string type uniformly to avoid conversion trouble 8 | - Supports RSAWithSHA1 and RSAWithSHA256 signature verification algorithms 9 | 10 | Get expansion pack: 11 | 12 | ``` 13 | go get github.com/wenzhenxi/gorsa 14 | ``` 15 | 16 | Specific use: 17 | 18 | 19 | ``` 20 | package main 21 | 22 | import ( 23 | "log" 24 | "errors" 25 | "github.com/wenzhenxi/gorsa" 26 | ) 27 | 28 | var Pubkey = `-----BEGIN Public key----- 29 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk+89V7vpOj1rG6bTAKYM 30 | 56qmFLwNCBVDJ3MltVVtxVUUByqc5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xb 31 | UAEZuA3EjlPHIaFIVIz04RaW10+1xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCW 32 | eItu1kNQ3MGdcuqKjke+LKhQ7nWPRCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331 33 | hWRB4DlYy8qFUmDsyvvExe4NjZWblXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDi 34 | aMD+Qt2Yp+Vvbz6hUiqIWSIH1BoHJer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvr 35 | MQIDAQAB 36 | -----END Public key----- 37 | ` 38 | 39 | var Pirvatekey = `-----BEGIN Private key----- 40 | MIIEpAIBAAKCAQEAk+89V7vpOj1rG6bTAKYM56qmFLwNCBVDJ3MltVVtxVUUByqc 41 | 5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xbUAEZuA3EjlPHIaFIVIz04RaW10+1 42 | xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCWeItu1kNQ3MGdcuqKjke+LKhQ7nWP 43 | RCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331hWRB4DlYy8qFUmDsyvvExe4NjZWb 44 | lXCqkEXRRAhi2SQRCl3teGuIHtDUxCskRIDiaMD+Qt2Yp+Vvbz6hUiqIWSIH1BoH 45 | Jer/JOq2/O6X3cmuppU4AdVNgy8Bq236iXvrMQIDAQABAoIBAQCCbxZvHMfvCeg+ 46 | YUD5+W63dMcq0QPMdLLZPbWpxMEclH8sMm5UQ2SRueGY5UBNg0WkC/R64BzRIS6p 47 | jkcrZQu95rp+heUgeM3C4SmdIwtmyzwEa8uiSY7Fhbkiq/Rly6aN5eB0kmJpZfa1 48 | 6S9kTszdTFNVp9TMUAo7IIE6IheT1x0WcX7aOWVqp9MDXBHV5T0Tvt8vFrPTldFg 49 | IuK45t3tr83tDcx53uC8cL5Ui8leWQjPh4BgdhJ3/MGTDWg+LW2vlAb4x+aLcDJM 50 | CH6Rcb1b8hs9iLTDkdVw9KirYQH5mbACXZyDEaqj1I2KamJIU2qDuTnKxNoc96HY 51 | 2XMuSndhAoGBAMPwJuPuZqioJfNyS99x++ZTcVVwGRAbEvTvh6jPSGA0k3cYKgWR 52 | NnssMkHBzZa0p3/NmSwWc7LiL8whEFUDAp2ntvfPVJ19Xvm71gNUyCQ/hojqIAXy 53 | tsNT1gBUTCMtFZmAkUsjqdM/hUnJMM9zH+w4lt5QM2y/YkCThoI65BVbAoGBAMFI 54 | GsIbnJDNhVap7HfWcYmGOlWgEEEchG6Uq6Lbai9T8c7xMSFc6DQiNMmQUAlgDaMV 55 | b6izPK4KGQaXMFt5h7hekZgkbxCKBd9xsLM72bWhM/nd/HkZdHQqrNAPFhY6/S8C 56 | IjRnRfdhsjBIA8K73yiUCsQlHAauGfPzdHET8ktjAoGAQdxeZi1DapuirhMUN9Zr 57 | kr8nkE1uz0AafiRpmC+cp2Hk05pWvapTAtIXTo0jWu38g3QLcYtWdqGa6WWPxNOP 58 | NIkkcmXJjmqO2yjtRg9gevazdSAlhXpRPpTWkSPEt+o2oXNa40PomK54UhYDhyeu 59 | akuXQsD4mCw4jXZJN0suUZMCgYAgzpBcKjulCH19fFI69RdIdJQqPIUFyEViT7Hi 60 | bsPTTLham+3u78oqLzQukmRDcx5ddCIDzIicMfKVf8whertivAqSfHytnf/pMW8A 61 | vUPy5G3iF5/nHj76CNRUbHsfQtv+wqnzoyPpHZgVQeQBhcoXJSm+qV3cdGjLU6OM 62 | HgqeaQKBgQCnmL5SX7GSAeB0rSNugPp2GezAQj0H4OCc8kNrHK8RUvXIU9B2zKA2 63 | z/QUKFb1gIGcKxYr+LqQ25/+TGvINjuf6P3fVkHL0U8jOG0IqpPJXO3Vl9B8ewWL 64 | cFQVB/nQfmaMa4ChK0QEUe+Mqi++MwgYbRHx1lIOXEfUJO+PXrMekw== 65 | -----END Private key----- 66 | ` 67 | 68 | 69 | func main() { 70 | // Public key encryption private key decryption 71 | if err := applyPubEPriD(); err != nil { 72 | log.Println(err) 73 | } 74 | // Public key decryption private key encryption 75 | if err := applyPriEPubD(); err != nil { 76 | log.Println(err) 77 | } 78 | } 79 | 80 | // Public key encryption private key decryption 81 | func applyPubEPriD() error { 82 | pubenctypt, err := gorsa.PublicEncrypt(`hello world`,Pubkey) 83 | if err != nil { 84 | return err 85 | } 86 | 87 | pridecrypt, err := gorsa.PriKeyDecrypt(pubenctypt,Pirvatekey) 88 | if err != nil { 89 | return err 90 | } 91 | if string(pridecrypt) != `hello world` { 92 | return errors.New(`Decryption failed`) 93 | } 94 | return nil 95 | } 96 | 97 | // Public key decryption private key encryption 98 | func applyPriEPubD() error { 99 | prienctypt, err := gorsa.PriKeyEncrypt(`hello world`,Pirvatekey) 100 | if err != nil { 101 | return err 102 | } 103 | 104 | pubdecrypt, err := gorsa.PublicDecrypt(prienctypt,Pubkey) 105 | if err != nil { 106 | return err 107 | } 108 | if string(pubdecrypt) != `hello world` { 109 | return errors.New(`Decryption failed`) 110 | } 111 | return nil 112 | } 113 | 114 | ``` 115 | -------------------------------------------------------------------------------- /rsa.go: -------------------------------------------------------------------------------- 1 | package gorsa 2 | 3 | import ( 4 | "bytes" 5 | "crypto" 6 | "crypto/md5" 7 | "crypto/rand" 8 | "crypto/rsa" 9 | "crypto/sha1" 10 | "crypto/sha256" 11 | "encoding/base64" 12 | "errors" 13 | "io/ioutil" 14 | ) 15 | 16 | var RSA = &RSASecurity{} 17 | 18 | type RSASecurity struct { 19 | pubStr string //公钥字符串 20 | priStr string //私钥字符串 21 | pubkey *rsa.PublicKey //公钥 22 | prikey *rsa.PrivateKey //私钥 23 | } 24 | 25 | // 设置公钥 26 | func (rsas *RSASecurity) SetPublicKey(pubStr string) (err error) { 27 | rsas.pubStr = pubStr 28 | rsas.pubkey, err = rsas.GetPublickey() 29 | return err 30 | } 31 | 32 | // 设置私钥 33 | func (rsas *RSASecurity) SetPrivateKey(priStr string) (err error) { 34 | rsas.priStr = priStr 35 | rsas.prikey, err = rsas.GetPrivatekey() 36 | return err 37 | } 38 | 39 | // *rsa.PublicKey 40 | func (rsas *RSASecurity) GetPrivatekey() (*rsa.PrivateKey, error) { 41 | return getPriKey([]byte(rsas.priStr)) 42 | } 43 | 44 | // *rsa.PrivateKey 45 | func (rsas *RSASecurity) GetPublickey() (*rsa.PublicKey, error) { 46 | return getPubKey([]byte(rsas.pubStr)) 47 | } 48 | 49 | // 公钥加密 50 | func (rsas *RSASecurity) PubKeyENCTYPT(input []byte) ([]byte, error) { 51 | if rsas.pubkey == nil { 52 | return []byte(""), errors.New(`Please set the public key in advance`) 53 | } 54 | output := bytes.NewBuffer(nil) 55 | err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, true) 56 | if err != nil { 57 | return []byte(""), err 58 | } 59 | return ioutil.ReadAll(output) 60 | } 61 | 62 | // 公钥解密 63 | func (rsas *RSASecurity) PubKeyDECRYPT(input []byte) ([]byte, error) { 64 | if rsas.pubkey == nil { 65 | return []byte(""), errors.New(`Please set the public key in advance`) 66 | } 67 | output := bytes.NewBuffer(nil) 68 | err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, false) 69 | if err != nil { 70 | return []byte(""), err 71 | } 72 | return ioutil.ReadAll(output) 73 | } 74 | 75 | // 私钥加密 76 | func (rsas *RSASecurity) PriKeyENCTYPT(input []byte) ([]byte, error) { 77 | if rsas.prikey == nil { 78 | return []byte(""), errors.New(`Please set the private key in advance`) 79 | } 80 | output := bytes.NewBuffer(nil) 81 | err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, true) 82 | if err != nil { 83 | return []byte(""), err 84 | } 85 | return ioutil.ReadAll(output) 86 | } 87 | 88 | // 私钥解密 89 | func (rsas *RSASecurity) PriKeyDECRYPT(input []byte) ([]byte, error) { 90 | if rsas.prikey == nil { 91 | return []byte(""), errors.New(`Please set the private key in advance`) 92 | } 93 | output := bytes.NewBuffer(nil) 94 | err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, false) 95 | if err != nil { 96 | return []byte(""), err 97 | } 98 | 99 | return ioutil.ReadAll(output) 100 | } 101 | 102 | /** 103 | * 使用RSAWithMD5算法签名 104 | */ 105 | func (rsas *RSASecurity) SignMd5WithRsa(data string) (string, error) { 106 | md5Hash := md5.New() 107 | s_data := []byte(data) 108 | md5Hash.Write(s_data) 109 | hashed := md5Hash.Sum(nil) 110 | 111 | signByte, err := rsa.SignPKCS1v15(rand.Reader, rsas.prikey, crypto.MD5, hashed) 112 | sign := base64.StdEncoding.EncodeToString(signByte) 113 | return string(sign), err 114 | } 115 | 116 | /** 117 | * 使用RSAWithSHA1算法签名 118 | */ 119 | func (rsas *RSASecurity) SignSha1WithRsa(data string) (string, error) { 120 | sha1Hash := sha1.New() 121 | s_data := []byte(data) 122 | sha1Hash.Write(s_data) 123 | hashed := sha1Hash.Sum(nil) 124 | 125 | signByte, err := rsa.SignPKCS1v15(rand.Reader, rsas.prikey, crypto.SHA1, hashed) 126 | sign := base64.StdEncoding.EncodeToString(signByte) 127 | return string(sign), err 128 | } 129 | 130 | /** 131 | * 使用RSAWithSHA256算法签名 132 | */ 133 | func (rsas *RSASecurity) SignSha256WithRsa(data string) (string, error) { 134 | sha256Hash := sha256.New() 135 | s_data := []byte(data) 136 | sha256Hash.Write(s_data) 137 | hashed := sha256Hash.Sum(nil) 138 | 139 | signByte, err := rsa.SignPKCS1v15(rand.Reader, rsas.prikey, crypto.SHA256, hashed) 140 | sign := base64.StdEncoding.EncodeToString(signByte) 141 | return string(sign), err 142 | } 143 | 144 | /** 145 | * 使用RSAWithMD5验证签名 146 | */ 147 | func (rsas *RSASecurity) VerifySignMd5WithRsa(data string, signData string) error { 148 | sign, err := base64.StdEncoding.DecodeString(signData) 149 | if err != nil { 150 | return err 151 | } 152 | hash := md5.New() 153 | hash.Write([]byte(data)) 154 | return rsa.VerifyPKCS1v15(rsas.pubkey, crypto.MD5, hash.Sum(nil), sign) 155 | } 156 | 157 | /** 158 | * 使用RSAWithSHA1验证签名 159 | */ 160 | func (rsas *RSASecurity) VerifySignSha1WithRsa(data string, signData string) error { 161 | sign, err := base64.StdEncoding.DecodeString(signData) 162 | if err != nil { 163 | return err 164 | } 165 | hash := sha1.New() 166 | hash.Write([]byte(data)) 167 | return rsa.VerifyPKCS1v15(rsas.pubkey, crypto.SHA1, hash.Sum(nil), sign) 168 | } 169 | 170 | /** 171 | * 使用RSAWithSHA256验证签名 172 | */ 173 | func (rsas *RSASecurity) VerifySignSha256WithRsa(data string, signData string) error { 174 | sign, err := base64.StdEncoding.DecodeString(signData) 175 | if err != nil { 176 | return err 177 | } 178 | hash := sha256.New() 179 | hash.Write([]byte(data)) 180 | 181 | return rsa.VerifyPKCS1v15(rsas.pubkey, crypto.SHA256, hash.Sum(nil), sign) 182 | } 183 | -------------------------------------------------------------------------------- /example/JAVA.md: -------------------------------------------------------------------------------- 1 | # 对应java版本 2 | 3 | ```java 4 | package com.example.demo; 5 | 6 | import org.apache.commons.codec.binary.Base64; 7 | 8 | import javax.crypto.Cipher; 9 | import java.io.ByteArrayOutputStream; 10 | import java.security.*; 11 | import java.security.interfaces.RSAPrivateKey; 12 | import java.security.interfaces.RSAPublicKey; 13 | import java.security.spec.InvalidKeySpecException; 14 | import java.security.spec.PKCS8EncodedKeySpec; 15 | import java.security.spec.X509EncodedKeySpec; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | public class Main { 20 | public static final String CHARSET = "UTF-8"; 21 | public static final String RSA_ALGORITHM = "RSA"; 22 | public static final int KEY_SIZE = 1024; 23 | 24 | public static Map createKeys() { 25 | //为RSA算法创建一个KeyPairGenerator对象 26 | KeyPairGenerator kpg; 27 | try { 28 | kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM); 29 | } catch (NoSuchAlgorithmException e) { 30 | throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]"); 31 | } 32 | 33 | //初始化KeyPairGenerator对象,密钥长度 34 | kpg.initialize(KEY_SIZE); 35 | //生成密匙对 36 | KeyPair keyPair = kpg.generateKeyPair(); 37 | //得到公钥 38 | Key publicKey = keyPair.getPublic(); 39 | String publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded()); 40 | //得到私钥 41 | Key privateKey = keyPair.getPrivate(); 42 | String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded()); 43 | Map keyPairMap = new HashMap(); 44 | keyPairMap.put("publicKey", publicKeyStr); 45 | keyPairMap.put("privateKey", privateKeyStr); 46 | 47 | return keyPairMap; 48 | } 49 | 50 | public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { 51 | //通过X509编码的Key指令获得公钥对象 52 | KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); 53 | X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey)); 54 | RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec); 55 | return key; 56 | } 57 | 58 | 59 | public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException { 60 | //通过PKCS#8编码的Key指令获得私钥对象 61 | KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); 62 | PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)); 63 | RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec); 64 | return key; 65 | } 66 | 67 | public static String privateEncrypt(String data, RSAPrivateKey privateKey) { 68 | try { 69 | Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); 70 | cipher.init(Cipher.ENCRYPT_MODE, privateKey); 71 | 72 | return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength())); 73 | } catch (Exception e) { 74 | throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e); 75 | } 76 | } 77 | 78 | 79 | public static String publicDecrypt(String data, RSAPublicKey publicKey) { 80 | try { 81 | Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); 82 | cipher.init(Cipher.DECRYPT_MODE, publicKey); 83 | return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET); 84 | } catch (Exception e) { 85 | throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e); 86 | } 87 | } 88 | 89 | private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) { 90 | int maxBlock = 0; 91 | if (opmode == Cipher.DECRYPT_MODE) { 92 | maxBlock = keySize / 8; 93 | } else { 94 | maxBlock = keySize / 8 - 11; // 加密 95 | } 96 | 97 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 98 | int offSet = 0; 99 | byte[] buff; 100 | int i = 0; 101 | try { 102 | while (datas.length > offSet) { 103 | if (datas.length - offSet > maxBlock) { 104 | buff = cipher.doFinal(datas, offSet, maxBlock); 105 | } else { 106 | buff = cipher.doFinal(datas, offSet, datas.length - offSet); 107 | } 108 | out.write(buff, 0, buff.length); 109 | i++; 110 | offSet = i * maxBlock; 111 | } 112 | } catch (Exception e) { 113 | e.getMessage(); 114 | } 115 | byte[] resultDatas = out.toByteArray(); 116 | try { 117 | out.close(); 118 | } catch (Exception e) { 119 | e.getMessage(); 120 | } 121 | return resultDatas; 122 | } 123 | 124 | public static String toHexString(String s) { 125 | String str = ""; 126 | for (int i = 0; i < s.length(); i++) { 127 | int ch = (int) s.charAt(i); 128 | str += Integer.toHexString(ch); 129 | } 130 | return str; 131 | } 132 | 133 | 134 | /** 135 | * 16进制字符串转换为字符串 136 | * 137 | * @param s 138 | * @return 139 | */ 140 | public static String hexStringToString(String s) { 141 | if (s == null || s.equals("")) { 142 | return null; 143 | } 144 | s = s.replace(" ", ""); 145 | byte[] baKeyword = new byte[s.length() / 2]; 146 | for (int i = 0; i < baKeyword.length; i++) { 147 | try { 148 | baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16)); 149 | } catch (Exception e) { 150 | e.printStackTrace(); 151 | } 152 | } 153 | try { 154 | s = new String(baKeyword, "gbk"); 155 | new String(); 156 | } catch (Exception e1) { 157 | e1.printStackTrace(); 158 | } 159 | return s; 160 | } 161 | 162 | public static void main(String[] args) throws Exception { 163 | Map keyMap = createKeys(); 164 | String publicKey = keyMap.get("publicKey"); 165 | String privateKey = keyMap.get("privateKey"); 166 | System.out.println("公钥: \n\r" + publicKey); 167 | System.out.println("私钥: \n\r" + privateKey); 168 | System.out.println("私钥加密——公钥解密"); 169 | 170 | String str = "{\"domainId\":\"ssotest\",\"externalUserId\":\"A0001\",\"timestamp\":1672502400}"; 171 | System.out.println("\r明文:\r\n" + str); 172 | 173 | String encodedData = privateEncrypt(str, getPrivateKey(privateKey)); 174 | System.out.println("密文:\r\n" + toHexString(encodedData)); 175 | 176 | String decodedData = publicDecrypt(encodedData, getPublicKey(publicKey)); 177 | System.out.println("解密后文字: \r\n" + decodedData); 178 | 179 | // String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIeiSgcWa8kiEqMzvqV0BTd8MGAi5fw0WMxVXv58VghIc9t30czF4D289ce+0aJh/DR2ZIWrBzEDjrda07tdBDU27kcTniJ3T2DVPNAOFcpVUA20OIok0BRBYK7Ac8iqJccJB/q/TXKdHyNHbPjQ6kwp7Wx2cQCWh5j2rWXXzW9vAgMBAAECgYB6K9yydaexDFftWXaoYdExIVQRxF2UxzIVG/DtGeIEo/53+X2pDbPm6IYa3e7GbaxXNS1mmZ9oruOmlNGTOz3FwWJN+C33WQMLBOlO2gUQSqLZ4X8EvTEBiMvF42U5pDqyAh0EgGtDL4TtA34CgEyX7Iw7rKgfhVvE1OWuDiQ3QQJBAL7rQZt0RARAEqG+WAEPWaN3iUsLkiClZnyfF3hVQug3n/OVSDm7iuKZyYRHIEanTGrfabq7fPw/qD+4fJcMj00CQQC13obu3bhBwCc01ApWR6cy4+liKexpGTvUK+5LpPiM72jFhPyRXdmYsdeXmE6SuxIYDx6xJVip4O1YuC99YxOrAkBjDkas9Gbx2ZiRKOQaMK+ue6/VKvy3SXniQNz5hys+ttWbmSGvKpoFtgrzQcACSH0CmkYOJ4bSjeiqnvqtmEulAkEAkjtdtTxzhfKR06lWsm8kogedRP++hfbzIzM7hHkeHHv3ezHlvqB+cIc2eT7Olq5x6wRlQjxsIROo47gc/y2lxwJAazp24jLnV9kGT6+hC8k79z9kFqs9x8H7Vil1IF/ciwSMSHq4IlT2X8CkgyR6iAZd9SNU24tcj05uVbpP14zC+g=="; 180 | // String encodedData = privateEncrypt(str, getPrivateKey(privateKey)); 181 | // System.out.println(encodedData.toString()); 182 | // System.out.println("密文:\r\n" + toHexString(encodedData)); 183 | 184 | // String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHokoHFmvJIhKjM76ldAU3fDBgIuX8NFjMVV7+fFYISHPbd9HMxeA9vPXHvtGiYfw0dmSFqwcxA463WtO7XQQ1Nu5HE54id09g1TzQDhXKVVANtDiKJNAUQWCuwHPIqiXHCQf6v01ynR8jR2z40OpMKe1sdnEAloeY9q1l181vbwIDAQAB"; 185 | // String encodedData = "QyNDS8CxI2ziE5Jz0jIBnJLy/L8lsXIpGhouhXw2DnEJ8ZxgnWHoEpHR8sPmbVzOCYvJQ5e4pSrYlGtwtry8bcR4Kn4W2P7XfeIhzTGKWwJFdSyUZeD2AmBMnV25xOoIUQ7BARt58rqy/M+v692ndReXtlshn7ce8FNPexGXlVk="; 186 | // String decodedData = publicDecrypt(encodedData, getPublicKey(publicKey)); 187 | // System.out.println("GO加密,Java解密后文字: \r\n" + decodedData); 188 | 189 | } 190 | } 191 | 192 | ``` 193 | -------------------------------------------------------------------------------- /rsa_ext.go: -------------------------------------------------------------------------------- 1 | package gorsa 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | "crypto/x509" 8 | "encoding/pem" 9 | "errors" 10 | "io" 11 | "io/ioutil" 12 | "math/big" 13 | ) 14 | 15 | var ( 16 | ErrDataToLarge = errors.New("message too long for RSA public key size") 17 | ErrDataLen = errors.New("data length error") 18 | ErrDataBroken = errors.New("data broken, first byte is not zero") 19 | ErrKeyPairDismatch = errors.New("data is not encrypted by the private key") 20 | ErrDecryption = errors.New("decryption error") 21 | ErrPublicKey = errors.New("get public key error") 22 | ErrPrivateKey = errors.New("get private key error") 23 | ) 24 | 25 | // 设置公钥 26 | func getPubKey(publickey []byte) (*rsa.PublicKey, error) { 27 | // decode public key 28 | block, _ := pem.Decode(publickey) 29 | if block == nil { 30 | return nil, errors.New("get public key error") 31 | } 32 | // x509 parse public key 33 | pub, err := x509.ParsePKIXPublicKey(block.Bytes) 34 | if err != nil { 35 | pub, err = x509.ParsePKCS1PublicKey(block.Bytes) 36 | if err != nil { 37 | return nil, err 38 | } 39 | } 40 | return pub.(*rsa.PublicKey), err 41 | } 42 | 43 | // 设置私钥 44 | func getPriKey(privatekey []byte) (*rsa.PrivateKey, error) { 45 | block, _ := pem.Decode(privatekey) 46 | if block == nil { 47 | return nil, errors.New("get private key error") 48 | } 49 | pri, err := x509.ParsePKCS1PrivateKey(block.Bytes) 50 | if err == nil { 51 | return pri, nil 52 | } 53 | pri2, err := x509.ParsePKCS8PrivateKey(block.Bytes) 54 | if err != nil { 55 | return nil, err 56 | } 57 | return pri2.(*rsa.PrivateKey), nil 58 | } 59 | 60 | // 公钥加密或解密byte 61 | func pubKeyByte(pub *rsa.PublicKey, in []byte, isEncrytp bool) ([]byte, error) { 62 | k := (pub.N.BitLen() + 7) / 8 63 | if isEncrytp { 64 | k = k - 11 65 | } 66 | if len(in) <= k { 67 | if isEncrytp { 68 | return rsa.EncryptPKCS1v15(rand.Reader, pub, in) 69 | } else { 70 | return pubKeyDecrypt(pub, in) 71 | } 72 | } else { 73 | iv := make([]byte, k) 74 | out := bytes.NewBuffer(iv) 75 | if err := pubKeyIO(pub, bytes.NewReader(in), out, isEncrytp); err != nil { 76 | return nil, err 77 | } 78 | return ioutil.ReadAll(out) 79 | } 80 | } 81 | 82 | // 私钥加密或解密byte 83 | func priKeyByte(pri *rsa.PrivateKey, in []byte, isEncrytp bool) ([]byte, error) { 84 | k := (pri.N.BitLen() + 7) / 8 85 | if isEncrytp { 86 | k = k - 11 87 | } 88 | if len(in) <= k { 89 | if isEncrytp { 90 | return priKeyEncrypt(rand.Reader, pri, in) 91 | } else { 92 | return rsa.DecryptPKCS1v15(rand.Reader, pri, in) 93 | } 94 | } else { 95 | iv := make([]byte, k) 96 | out := bytes.NewBuffer(iv) 97 | if err := priKeyIO(pri, bytes.NewReader(in), out, isEncrytp); err != nil { 98 | return nil, err 99 | } 100 | return ioutil.ReadAll(out) 101 | } 102 | } 103 | 104 | // 公钥加密或解密Reader 105 | func pubKeyIO(pub *rsa.PublicKey, in io.Reader, out io.Writer, isEncrytp bool) (err error) { 106 | k := (pub.N.BitLen() + 7) / 8 107 | if isEncrytp { 108 | k = k - 11 109 | } 110 | buf := make([]byte, k) 111 | var b []byte 112 | size := 0 113 | for { 114 | size, err = in.Read(buf) 115 | if err != nil { 116 | if err == io.EOF { 117 | return nil 118 | } 119 | return err 120 | } 121 | if size < k { 122 | b = buf[:size] 123 | } else { 124 | b = buf 125 | } 126 | if isEncrytp { 127 | b, err = rsa.EncryptPKCS1v15(rand.Reader, pub, b) 128 | } else { 129 | b, err = pubKeyDecrypt(pub, b) 130 | } 131 | if err != nil { 132 | return err 133 | } 134 | if _, err = out.Write(b); err != nil { 135 | return err 136 | } 137 | } 138 | return nil 139 | } 140 | 141 | // 私钥加密或解密Reader 142 | func priKeyIO(pri *rsa.PrivateKey, r io.Reader, w io.Writer, isEncrytp bool) (err error) { 143 | k := (pri.N.BitLen() + 7) / 8 144 | if isEncrytp { 145 | k = k - 11 146 | } 147 | buf := make([]byte, k) 148 | var b []byte 149 | size := 0 150 | for { 151 | size, err = r.Read(buf) 152 | if err != nil { 153 | if err == io.EOF { 154 | return nil 155 | } 156 | return err 157 | } 158 | if size < k { 159 | b = buf[:size] 160 | } else { 161 | b = buf 162 | } 163 | if isEncrytp { 164 | b, err = priKeyEncrypt(rand.Reader, pri, b) 165 | } else { 166 | b, err = rsa.DecryptPKCS1v15(rand.Reader, pri, b) 167 | } 168 | if err != nil { 169 | return err 170 | } 171 | if _, err = w.Write(b); err != nil { 172 | return err 173 | } 174 | } 175 | return nil 176 | } 177 | 178 | // 公钥解密 179 | func pubKeyDecrypt(pub *rsa.PublicKey, data []byte) ([]byte, error) { 180 | k := (pub.N.BitLen() + 7) / 8 181 | if k != len(data) { 182 | return nil, ErrDataLen 183 | } 184 | m := new(big.Int).SetBytes(data) 185 | if m.Cmp(pub.N) > 0 { 186 | return nil, ErrDataToLarge 187 | } 188 | m.Exp(m, big.NewInt(int64(pub.E)), pub.N) 189 | d := leftPad(m.Bytes(), k) 190 | if d[0] != 0 { 191 | return nil, ErrDataBroken 192 | } 193 | if d[1] != 0 && d[1] != 1 { 194 | return nil, ErrKeyPairDismatch 195 | } 196 | var i = 2 197 | for ; i < len(d); i++ { 198 | if d[i] == 0 { 199 | break 200 | } 201 | } 202 | i++ 203 | if i == len(d) { 204 | return nil, nil 205 | } 206 | return d[i:], nil 207 | } 208 | 209 | // 私钥加密 210 | func priKeyEncrypt(rand io.Reader, priv *rsa.PrivateKey, hashed []byte) ([]byte, error) { 211 | tLen := len(hashed) 212 | k := (priv.N.BitLen() + 7) / 8 213 | if k < tLen+11 { 214 | return nil, ErrDataLen 215 | } 216 | em := make([]byte, k) 217 | em[1] = 1 218 | for i := 2; i < k-tLen-1; i++ { 219 | em[i] = 0xff 220 | } 221 | copy(em[k-tLen:k], hashed) 222 | m := new(big.Int).SetBytes(em) 223 | c, err := decrypt(rand, priv, m) 224 | if err != nil { 225 | return nil, err 226 | } 227 | copyWithLeftPad(em, c.Bytes()) 228 | return em, nil 229 | } 230 | 231 | // 从crypto/rsa复制 232 | var bigZero = big.NewInt(0) 233 | var bigOne = big.NewInt(1) 234 | 235 | // 从crypto/rsa复制 236 | func encrypt(c *big.Int, pub *rsa.PublicKey, m *big.Int) *big.Int { 237 | e := big.NewInt(int64(pub.E)) 238 | c.Exp(m, e, pub.N) 239 | return c 240 | } 241 | 242 | // 从crypto/rsa复制 243 | func decrypt(random io.Reader, priv *rsa.PrivateKey, c *big.Int) (m *big.Int, err error) { 244 | if c.Cmp(priv.N) > 0 { 245 | err = ErrDecryption 246 | return 247 | } 248 | var ir *big.Int 249 | if random != nil { 250 | var r *big.Int 251 | 252 | for { 253 | r, err = rand.Int(random, priv.N) 254 | if err != nil { 255 | return 256 | } 257 | if r.Cmp(bigZero) == 0 { 258 | r = bigOne 259 | } 260 | var ok bool 261 | ir, ok = modInverse(r, priv.N) 262 | if ok { 263 | break 264 | } 265 | } 266 | bigE := big.NewInt(int64(priv.E)) 267 | rpowe := new(big.Int).Exp(r, bigE, priv.N) 268 | cCopy := new(big.Int).Set(c) 269 | cCopy.Mul(cCopy, rpowe) 270 | cCopy.Mod(cCopy, priv.N) 271 | c = cCopy 272 | } 273 | if priv.Precomputed.Dp == nil { 274 | m = new(big.Int).Exp(c, priv.D, priv.N) 275 | } else { 276 | m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0]) 277 | m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1]) 278 | m.Sub(m, m2) 279 | if m.Sign() < 0 { 280 | m.Add(m, priv.Primes[0]) 281 | } 282 | m.Mul(m, priv.Precomputed.Qinv) 283 | m.Mod(m, priv.Primes[0]) 284 | m.Mul(m, priv.Primes[1]) 285 | m.Add(m, m2) 286 | 287 | for i, values := range priv.Precomputed.CRTValues { 288 | prime := priv.Primes[2+i] 289 | m2.Exp(c, values.Exp, prime) 290 | m2.Sub(m2, m) 291 | m2.Mul(m2, values.Coeff) 292 | m2.Mod(m2, prime) 293 | if m2.Sign() < 0 { 294 | m2.Add(m2, prime) 295 | } 296 | m2.Mul(m2, values.R) 297 | m.Add(m, m2) 298 | } 299 | } 300 | if ir != nil { 301 | m.Mul(m, ir) 302 | m.Mod(m, priv.N) 303 | } 304 | 305 | return 306 | } 307 | 308 | // 从crypto/rsa复制 309 | func copyWithLeftPad(dest, src []byte) { 310 | numPaddingBytes := len(dest) - len(src) 311 | for i := 0; i < numPaddingBytes; i++ { 312 | dest[i] = 0 313 | } 314 | copy(dest[numPaddingBytes:], src) 315 | } 316 | 317 | // 从crypto/rsa复制 318 | func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) { 319 | _, err = io.ReadFull(rand, s) 320 | if err != nil { 321 | return 322 | } 323 | for i := 0; i < len(s); i++ { 324 | for s[i] == 0 { 325 | _, err = io.ReadFull(rand, s[i:i+1]) 326 | if err != nil { 327 | return 328 | } 329 | s[i] ^= 0x42 330 | } 331 | } 332 | return 333 | } 334 | 335 | // 从crypto/rsa复制 336 | func leftPad(input []byte, size int) (out []byte) { 337 | n := len(input) 338 | if n > size { 339 | n = size 340 | } 341 | out = make([]byte, size) 342 | copy(out[len(out)-n:], input) 343 | return 344 | } 345 | 346 | // 从crypto/rsa复制 347 | func modInverse(a, n *big.Int) (ia *big.Int, ok bool) { 348 | g := new(big.Int) 349 | x := new(big.Int) 350 | y := new(big.Int) 351 | g.GCD(x, y, a, n) 352 | if g.Cmp(bigOne) != 0 { 353 | return 354 | } 355 | if x.Cmp(bigOne) < 0 { 356 | x.Add(x, n) 357 | } 358 | return x, true 359 | } 360 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------