func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) { rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey) rsaPriv := new(rsa.PrivateKey) rsaPriv.PublicKey = *rsaPub buf := bytes.NewBuffer(data) d, _, err := readMPI(buf) if err != nil { return } p, _, err := readMPI(buf) if err != nil { return } q, _, err := readMPI(buf) if err != nil { return } rsaPriv.D = new(big.Int).SetBytes(d) rsaPriv.Primes = make([]*big.Int, 2) rsaPriv.Primes[0] = new(big.Int).SetBytes(p) rsaPriv.Primes[1] = new(big.Int).SetBytes(q) if err := rsaPriv.Validate(); err != nil { return err } rsaPriv.Precompute() pk.PrivateKey = rsaPriv pk.Encrypted = false pk.encryptedData = nil return nil }
func (s *server) insertIdentity(req []byte) error { var record struct { Type string `sshtype:"17"` Rest []byte `ssh:"rest"` } if err := ssh.Unmarshal(req, &record); err != nil { return err } switch record.Type { case ssh.KeyAlgoRSA: var k rsaKeyMsg if err := ssh.Unmarshal(req, &k); err != nil { return err } priv := rsa.PrivateKey{ PublicKey: rsa.PublicKey{ E: int(k.E.Int64()), N: k.N, }, D: k.D, Primes: []*big.Int{k.P, k.Q}, } priv.Precompute() return s.agent.Add(AddedKey{PrivateKey: &priv, Comment: k.Comments}) } return fmt.Errorf("not implemented: %s", record.Type) }
//Generate is use to create a pair of keys (Private and Public) you can specify if you want to save them in a file, // the path is defined by PrivateKeyPath and PublicKeyPath global variable func Generate(identifier string, save bool) (*rsa.PrivateKey, *rsa.PublicKey, error) { var publickey *rsa.PublicKey var privatekey *rsa.PrivateKey privatekey, err := rsa.GenerateKey(rand.Reader, 1024) if err != nil { return nil, nil, err } privatekey.Precompute() err = privatekey.Validate() if err != nil { return nil, nil, err } publickey = &privatekey.PublicKey if save == true { savePrivateKey(privatekey, PrivateKeyPath) savePublicKey(publickey, identifier, PublicKeyPath) } return privatekey, publickey, nil }
// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form. func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte { key.Precompute() version := 0 if len(key.Primes) > 2 { version = 1 } priv := pkcs1PrivateKey{ Version: version, N: key.N, E: key.PublicKey.E, D: key.D, P: key.Primes[0], Q: key.Primes[1], Dp: key.Precomputed.Dp, Dq: key.Precomputed.Dq, Qinv: key.Precomputed.Qinv, } priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues)) for i, values := range key.Precomputed.CRTValues { priv.AdditionalPrimes[i].Prime = key.Primes[2+i] priv.AdditionalPrimes[i].Exp = values.Exp priv.AdditionalPrimes[i].Coeff = values.Coeff } b, _ := asn1.Marshal(priv) return b }
// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form. func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte { key.Precompute() version := 0 if len(key.Primes) > 2 { version = 1 } priv := pkcs1PrivateKey{ Version: version, N: rawValueForBig(key.N), E: key.PublicKey.E, D: rawValueForBig(key.D), P: rawValueForBig(key.Primes[0]), Q: rawValueForBig(key.Primes[1]), Dp: rawValueForBig(key.Precomputed.Dp), Dq: rawValueForBig(key.Precomputed.Dq), Qinv: rawValueForBig(key.Precomputed.Qinv), } priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues)) for i, values := range key.Precomputed.CRTValues { priv.AdditionalPrimes[i].Prime = rawValueForBig(key.Primes[2+i]) priv.AdditionalPrimes[i].Exp = rawValueForBig(values.Exp) priv.AdditionalPrimes[i].Coeff = rawValueForBig(values.Coeff) } b, _ := asn1.Marshal(priv) return b }
func NewRsaEncrypt(privateKeyInput io.Reader, keyBytes int, newHash func() hash.Hash) (*RsaEncrypt, error) { data, err := ioutil.ReadAll(privateKeyInput) if err != nil { return nil, err } var block *pem.Block if block, _ = pem.Decode(data); block == nil || block.Type != "RSA PRIVATE KEY" { return nil, errors.New("wrong private key") } var privateKey *rsa.PrivateKey if privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { return nil, err } privateKey.Precompute() if err = privateKey.Validate(); err != nil { return nil, err } h := newHash() r := &RsaEncrypt{ privateKey: privateKey, keyBytes: keyBytes, maxMsgBytes: keyBytes - (h.Size()*2 + 2), newHash: newHash, } return r, nil }
// ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form. func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) { var priv pkcs1PrivateKey rest, err := asn1.Unmarshal(der, &priv) if len(rest) > 0 { return nil, asn1.SyntaxError{Msg: "trailing data"} } if err != nil { return nil, err } if priv.Version > 1 { return nil, errors.New("x509: unsupported private key version") } if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 { return nil, errors.New("x509: private key contains zero or negative value") } key := new(rsa.PrivateKey) key.PublicKey = rsa.PublicKey{ E: priv.E, N: priv.N, } key.D = priv.D key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes)) key.Primes[0] = priv.P key.Primes[1] = priv.Q for i, a := range priv.AdditionalPrimes { if a.Prime.Sign() <= 0 { return nil, errors.New("x509: private key contains zero or negative prime") } key.Primes[i+2] = a.Prime // We ignore the other two values because rsa will calculate // them as needed. } err = key.Validate() if err != nil { return nil, err } key.Precompute() return key, nil }
func parseRSACert(req []byte) (*AddedKey, error) { var k rsaCertMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } pubKey, err := ssh.ParsePublicKey(k.CertBytes) if err != nil { return nil, err } cert, ok := pubKey.(*ssh.Certificate) if !ok { return nil, errors.New("agent: bad RSA certificate") } // An RSA publickey as marshaled by rsaPublicKey.Marshal() in keys.go var rsaPub struct { Name string E *big.Int N *big.Int } if err := ssh.Unmarshal(cert.Key.Marshal(), &rsaPub); err != nil { return nil, fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err) } if rsaPub.E.BitLen() > 30 { return nil, errors.New("agent: RSA public exponent too large") } priv := rsa.PrivateKey{ PublicKey: rsa.PublicKey{ E: int(rsaPub.E.Int64()), N: rsaPub.N, }, D: k.D, Primes: []*big.Int{k.Q, k.P}, } priv.Precompute() return &AddedKey{PrivateKey: &priv, Certificate: cert, Comment: k.Comments}, nil }
// GenerateKeys creates a public and private key for the current transfer // returns both func GenerateKeys() (*rsa.PublicKey, *rsa.PrivateKey) { var publicKey *rsa.PublicKey var privateKey *rsa.PrivateKey var err error // Generate Private Key if privateKey, err = rsa.GenerateKey(rand.Reader, 1024); err != nil { log.Fatal(err) } // Validate Private Key -- Sanity checks on the key if err = privateKey.Validate(); err != nil { log.Fatal(err) } // Precompute some calculations speeds up private key operations in the future privateKey.Precompute() //Public key address (of an RSA key) publicKey = &privateKey.PublicKey return publicKey, privateKey }
func TestRsa() { var private_key *rsa.PrivateKey var public_key *rsa.PublicKey var plain_text, encrypted, decrypted, label []byte var err error plain_text = []byte("Plain text message to be encrypted") //Generate Private Key if private_key, err = rsa.GenerateKey(rand.Reader, 1024); err != nil { log.Fatal(err) } fmt.Println(private_key) // Precompute some calculations -- Calculations that speed up private key operations in the future private_key.Precompute() //Validate Private Key -- Sanity checks on the key if err = private_key.Validate(); err != nil { log.Fatal(err) } //Public key address (of an RSA key) public_key = &private_key.PublicKey encrypted = Encrypt_oaep(public_key, plain_text, label) decrypted = Decrypt_oaep(private_key, encrypted, label) fmt.Printf("OAEP Encrypted [%s] to \n[%x]\n", string(plain_text), encrypted) fmt.Printf("OAEP Decrypted [%x] to \n[%s]\n", encrypted, decrypted) // To use existing private key (Skipping the GenerateKey, Precompute, Validation steps shown above) // This reads pem file and retrieves the public, private key needed to encrypt data //use_exsiting_keys() }
func main() { message := []byte("MODULUS") message_p := []byte("PRIME Pea") pb := make([]byte, 32) pb[0] = 0x80 for i, c := range message { pb[i] |= c >> 7 pb[i+1] |= c << 1 } copy(pb[len(message)+2:], message_p) p, err := PrimeWithPrefix(pb, 512) if err != nil { panic(err) } qb := make([]byte, 33) message_q := []byte("PRIME Queue") qb[0] = 0x80 copy(qb[len(message)+2:], message_q) q, err := PrimeWithPrefix(qb, 512) if err != nil { panic(err) } n := big.NewInt(0) n.Mul(p, q) // To calculate the modulus from the desired private key, we need simply to // invert it modulo (p-1)(q-1) phi_p := big.NewInt(-1) phi_p.Add(phi_p, p) phi_q := big.NewInt(-1) phi_q.Add(phi_q, q) phi := big.NewInt(0) phi.Mul(phi_p, phi_q) d := big.NewInt(0x10001) d.ModInverse(d, phi) private := new(rsa.PrivateKey) private.N = n private.E = 0x10001 private.D = d private.Primes = []*big.Int{p, q} private.Precompute() rfckey := rfc3441PrivateKey{Version: 0, Modulus: n, PublicExponent: 0x10001, PrivateExponent: d, Prime1: p, Prime2: q, Exponent1: private.Precomputed.Dp, Exponent2: private.Precomputed.Dq, Coefficient: private.Precomputed.Qinv} priv_enc, err := asn1.Marshal(rfckey) if err != nil { panic(err) } b := pem.Block{Type: "RSA PRIVATE KEY", Bytes: priv_enc} pem.Encode(os.Stdout, &b) }