~cmars/tsssh/trunk2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
   Konec - Public key crypto with OpenSSH keys.
   Copyright (C) 2012  Casey Marshall <casey.marshall@gmail.com>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package konec

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/pem"
	//"fmt"
	"crypto/x509"
	"io"
	"io/ioutil"
	//"bitbucket.org/cmars/go.crypto/ssh"
)

type SshRsaPrivKey struct {
	*rsa.PrivateKey
}

func ReadPrivKey(r io.Reader) (sk *SshRsaPrivKey, err error) {
	pemContents, err := ioutil.ReadAll(r)
	if err != nil {
		panic(err)
	}
	block, _ := pem.Decode(pemContents)
	// TODO: support DEK passphrase protected private key cert
	rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		panic(err)
	}
	sk = &SshRsaPrivKey{PrivateKey: rsakey}
	return
}

func (sk *SshRsaPrivKey) Decrypt(ciphertext []byte) (plaintext []byte, err error) {
	return rsa.DecryptOAEP(sha1.New(), rand.Reader, sk.PrivateKey, ciphertext, nil)
}

func (sk *SshRsaPrivKey) Sign(msg []byte) (sig []byte, err error) {
	h := sha256.New()
	h.Write(msg)
	digest := h.Sum(nil)
	h.Reset()
	return rsa.SignPKCS1v15(rand.Reader, sk.PrivateKey, crypto.SHA256, digest)
}