Beispiel #1
0
// Encrypt the given payload. Based on the key encryption algorithm,
// this will either use RSA-PKCS1v1.5 or RSA-OAEP (with SHA-1 or SHA-256).
func (ctx rsaEncrypterVerifier) encrypt(cek []byte, alg KeyAlgorithm) ([]byte, error) {
	switch alg {
	case RSA1_5:
		return rsa.EncryptPKCS1v15(randReader, ctx.publicKey, cek)
	case RSA_OAEP:
		return rsa.EncryptOAEP(sha1.New(), randReader, ctx.publicKey, cek, []byte{})
	case RSA_OAEP_256:
		return rsa.EncryptOAEP(sha256.New(), randReader, ctx.publicKey, cek, []byte{})
	}

	return nil, ErrUnsupportedAlgorithm
}
Beispiel #2
0
func (enc *CryptorOAEP) EncryptOAEP(plaintextBytes []byte, label []byte) ([]byte, error) {
	if enc.RsaPublicKey == nil {
		err := errors.New("402: RSA Public Key Not Set")
		return []byte{}, err
	}
	return rsa.EncryptOAEP(enc.Hash, rand.Reader, enc.RsaPublicKey, plaintextBytes, label)
}
Beispiel #3
0
func (s secret) MarshalJSON() ([]byte, error) {
	m, err := rsa.EncryptOAEP(crypto.SHA512.New(), rand.Reader, key.Public().(*rsa.PublicKey), []byte(s), nil)
	if err != nil {
		return nil, err
	}
	return json.Marshal(base64.StdEncoding.EncodeToString(m))
}
Beispiel #4
0
func (s *SignedMessage) Encrypt(publicKey *rsa.PublicKey) (encrypted *EncryptedMessage, err error) {
	encrypted = new(EncryptedMessage)
	hash := sha256.New()

	//Join message and signature
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err = enc.Encode(s)
	if err != nil {
		return nil, err
	}

	//Split messages to parts acceptable by encrypter
	k := (publicKey.N.BitLen() + 7) / 8
	maxSize := k - 2*hash.Size() - 2 //from rsa.go
	toEncrypt := splitMsg(buf.Bytes(), maxSize)

	//encrypt
	parts := make([][]byte, len(toEncrypt))
	for i, part := range toEncrypt {
		parts[i], err = rsa.EncryptOAEP(hash, rand.Reader, publicKey, part, nil)
		if err != nil {
			return nil, err
		}
	}

	encrypted.Msg = parts
	return encrypted, nil
}
Beispiel #5
0
// Encrypt encrypts a given plaintext using the provided public key.
// The encryption process uses random data. Therefore, this function is not deterministic.
func Encrypt(publicKey *rsa.PublicKey, plaintext []byte) (EncryptedMessage, error) {
	if publicKey == nil {
		return EncryptedMessage{}, errors.New("public key must not be nil")
	}

	aesKey, err := generateSymmetricKey()
	if err != nil {
		return EncryptedMessage{}, err
	}

	ciphertext, err := symmetricEncrypt(aesKey, plaintext)
	if err != nil {
		return EncryptedMessage{}, err
	}

	encryptedKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, aesKey, nil)
	if err != nil {
		return EncryptedMessage{}, err
	}

	return EncryptedMessage{
		Ciphertext:   ciphertext,
		EncryptedKey: encryptedKey,
	}, nil
}
Beispiel #6
0
func TestPad(t *testing.T) {
	private, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil || private == nil {
		t.Fatal("Can't gen private key %s\n", err)
	}
	public := &private.PublicKey
	var a [9]byte
	copy(a[0:8], "IDENTITY")

	seed := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
	encrypted_secret, err := rsa.EncryptOAEP(sha1.New(), rand.Reader,
		public, seed, a[0:9])
	if err != nil {
		t.Fatal("Can't encrypt ", err)
	}
	fmt.Printf("encrypted_secret: %x\n", encrypted_secret)
	decrypted_secret, err := rsa.DecryptOAEP(sha1.New(), rand.Reader,
		private, encrypted_secret, a[0:9])
	if err != nil {
		t.Fatal("Can't decrypt ", err)
	}
	fmt.Printf("decrypted_secret: %x\n", decrypted_secret)
	var N *big.Int
	var D *big.Int
	var x *big.Int
	var z *big.Int
	N = public.N
	D = private.D
	x = new(big.Int)
	z = new(big.Int)
	x.SetBytes(encrypted_secret)
	z = z.Exp(x, D, N)
	decrypted_pad := z.Bytes()
	fmt.Printf("decrypted_pad   : %x\n", decrypted_pad)
}
Beispiel #7
0
func (t *rsaTransformer) Encrypt(value []byte) ([]byte, error) {
	encrypted, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, &t.rsaPrivateKey.PublicKey, value, nil)
	if err != nil {
		return nil, err
	}
	return []byte(EncodeToString(encrypted)), nil
}
Beispiel #8
0
func (e *rsaEncryptor) Encrypt(value []byte) ([]byte, error) {
	encrypted, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, e.rsaPublicKey, value, nil)
	if err != nil {
		return nil, err
	}
	return []byte(EncodeToString(encrypted)), nil
}
Beispiel #9
0
// returns a base64 encoded ciphertext.
// OAEP can only encrypt plaintexts that are smaller than the key length; for
// a 1024-bit key, about 117 bytes. So instead, this function:
// * generates a random 32-byte symmetric key (randKey)
// * encrypts the plaintext with AES256 using that random symmetric key -> cipherText
// * encrypts the random symmetric key with the ssh PublicKey -> cipherKey
// * returns the base64-encoded marshalled JSON for the ciphertext and key
func CredulousEncode(plaintext string, pubkey ssh.PublicKey) (ciphertext string, err error) {
	rsaKey := sshPubkeyToRsaPubkey(pubkey)
	randKey := make([]byte, 32)
	_, err = rand.Read(randKey)
	if err != nil {
		return "", err
	}

	encoded, err := encodeAES(randKey, plaintext)
	if err != nil {
		return "", err
	}

	out, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, &rsaKey, []byte(randKey), []byte("Credulous"))
	if err != nil {
		return "", err
	}
	cipherKey := base64.StdEncoding.EncodeToString(out)

	cipherStruct := AESEncryption{
		EncodedKey: cipherKey,
		Ciphertext: encoded,
	}

	tmp, err := json.Marshal(cipherStruct)
	if err != nil {
		return "", err
	}

	ciphertext = base64.StdEncoding.EncodeToString(tmp)

	return ciphertext, nil
}
Beispiel #10
0
// Create an AES IV and key and an 8-byte salt, then encrypt these and
// the proposed protocol version using the server's comms public key.
func ClientEncryptHello(version1 uint32, ck *rsa.PublicKey, rng *xr.PRNG) (
	cOneShot *AesSession, ciphertext []byte, err error) {

	if rng == nil {
		rng = xr.MakeSystemRNG()
	}
	vBytes := make([]byte, 4)
	vBytes[0] = byte(version1)
	vBytes[1] = byte(version1 >> 8)
	vBytes[2] = byte(version1 >> 16)
	vBytes[3] = byte(version1 >> 24)

	// Generate 32-byte AES key, and 8-byte salt for the Hello
	salty := make([]byte, 2*aes.BlockSize+8+20)
	rng.NextBytes(salty)

	key1 := salty[:2*aes.BlockSize]
	// salt1 := salty[2*aes.BlockSize : 2*aes.BlockSize+8]
	oaep1 := salty[2*aes.BlockSize+8:]
	oaepSalt := bytes.NewBuffer(oaep1)

	sha := sha1.New()
	data := salty[:2*aes.BlockSize+8] // contains key1,salt1
	data = append(data, vBytes...)    // ... plus preferred protocol version

	ciphertext, err = rsa.EncryptOAEP(sha, oaepSalt, ck, data, nil)
	if err == nil {
		cOneShot, err = NewAesSession(key1, rng)
	}
	return
}
Beispiel #11
0
// Encrypts a symmetric key to this identity
func (this *PublicIdentity) Encrypt(key *SymmetricKey) (ek *EncryptedKey) {
	out, err := rsa.EncryptOAEP(sha256.New224(), rand.Reader, this.key, key.key, nil)
	if err != nil {
		panic(err)
	}
	return &EncryptedKey{impl: out}
}
Beispiel #12
0
func main() {
	privateKey, err := rsa.GenerateKey(rand.Reader, 512)
	if err != nil {
		fmt.Printf("rsa.GenerateKey: %v\n", err)
	}

	message := "Hello World!"
	messageBytes := bytes.NewBufferString(message)
	sha1 := sha1.New()

	encrypted, err := rsa.EncryptOAEP(sha1, rand.Reader, &privateKey.PublicKey, messageBytes.Bytes(), nil)
	if err != nil {
		fmt.Printf("EncryptOAEP: %s\n", err)
	}

	decrypted, err := rsa.DecryptOAEP(sha1, rand.Reader, privateKey, encrypted, nil)
	if err != nil {
		fmt.Printf("decrypt: %s\n", err)
	}

	decryptedString := bytes.NewBuffer(decrypted).String()
	fmt.Printf("message: %v\n", message)
	fmt.Printf("encrypted: %v\n", encrypted)
	fmt.Printf("decryptedString: %v\n", decryptedString)
}
Beispiel #13
0
// Encrypts a message with the given public key using RSA-OAEP and the sha1 hash function.
func RSAEncrypt(pub *rsa.PublicKey, msg []byte) []byte {
	b, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, pub, msg, nil)
	if err != nil {
		panic(err)
	}
	return b
}
Beispiel #14
0
func (ct *CryptoTool) Enc(in []byte) []byte {
	out, err := rsa.EncryptOAEP(ct.sha1, rand.Reader, ct.publicKey, in, nil)
	if err != nil {
		log.Fatalln("EncryptOAEP fail", err)
	}
	return out
}
Beispiel #15
0
func encryptWithAPIPublicKey(publicKey *rsa.PublicKey, message []byte) []byte {
	encryptedMessage, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, publicKey, message, nil)
	if err != nil {
		return nil
	}

	return encryptedMessage
}
Beispiel #16
0
// encrypts a given message with a provided RSA public key.
// the label must be the same for the encryption and decryption for it to work.
func encryptRSA(pub *rsa.PublicKey, message []byte) []byte {
	label := make([]byte, 10)
	encMessage, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, pub, message, label)
	fmt.Println(encMessage)
	if err != nil {
		fmt.Println("encryption failed!: ", err)
	}
	return encMessage
}
// EncryptKey encrypts a 16-byte key with the RSA or EC key of the record.
func (pr PasswordRecord) EncryptKey(in []byte) (out []byte, err error) {
	if pr.Type == RSARecord {
		return rsa.EncryptOAEP(sha1.New(), rand.Reader, &pr.RSAKey.RSAPublic, in, nil)
	} else if pr.Type == ECCRecord {
		return ecdh.Encrypt(pr.ECKey.ECPublic, in)
	} else {
		return nil, errors.New("Invalid function for record type")
	}
}
Beispiel #18
0
// Encrypt encrypts the message with RSAES-OAEP, checking to ensure that it is
// not longer than the maximum allowed message length. It uses SHA256
// as the underlying hash algorithm.
func Encrypt(pub *rsa.PublicKey, pt []byte) (ct []byte, err error) {
	if len(pt) > MaxMessageLength(pub) {
		err = fmt.Errorf("message is too long")
		return
	}

	hash := sha256.New()
	ct, err = rsa.EncryptOAEP(hash, rand.Reader, pub, pt, defaultLabel)
	return
}
Beispiel #19
0
//Encrypt Encrypt the given message with the given public key.
func Encrypt(content []byte, publickey *rsa.PublicKey) ([]byte, error) {
	md5hash := md5.New()
	label := []byte("")

	encryptedmsg, err := rsa.EncryptOAEP(md5hash, rand.Reader, publickey, content, label)
	if err != nil {
		return nil, err
	}
	return encryptedmsg, nil
}
//OAEP Encrypt
func Encrypt_oaep(public_key *rsa.PublicKey, plain_text, label []byte) (encrypted []byte) {
	var err error
	var md5_hash hash.Hash

	md5_hash = md5.New()

	if encrypted, err = rsa.EncryptOAEP(md5_hash, rand.Reader, public_key, plain_text, label); err != nil {
		log.Fatal(err)
	}
	return
}
Beispiel #21
0
func (rk *rsaPublicKey) Encrypt(msg []byte) ([]byte, error) {
	// FIXME: If msg is too long for keysize, EncryptOAEP returns an error
	// Do we want to return a Keyczar error here, either by checking
	// ourselves for this case or by wrapping the returned error?
	s, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, &rk.key, msg, nil)
	if err != nil {
		return nil, err
	}
	h := append(makeHeader(rk), s...)
	return h, nil
}
func EncryptWithPublicKey(recipientPubKey *rsa.PublicKey, plainText []byte) (cipher []byte, failure error) {
	sha_hash := sha256.New()

	encrypted, err := rsa.EncryptOAEP(sha_hash, rand.Reader, recipientPubKey, plainText, label)

	if err != nil {
		return nil, err
	}

	return encrypted, nil
}
Beispiel #23
0
func signature(email, password string) (string, error) {
	hash := sha1.Sum(androidKeyBytes)
	msg := append([]byte(email), 0)
	msg = append(msg, []byte(password)...)
	encryptedLogin, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, androidKey, msg, nil)
	if err != nil {
		return "", err
	}
	sig := append([]byte{0}, hash[:4]...)
	sig = append(sig, encryptedLogin...)
	return base64.URLEncoding.EncodeToString(sig), nil
}
Beispiel #24
0
func main() {
	flag.Parse()

	// Read the input file
	in, err := ioutil.ReadFile(*inFile)
	if err != nil {
		log.Fatalf("input file: %s", err)
	}
	fmt.Println(len(in), in)

	// Read the private key
	pemData, err := ioutil.ReadFile(*keyFile)
	if err != nil {
		log.Fatalf("read key file: %s", err)
	}

	// Extract the PEM-encoded data block
	block, _ := pem.Decode(pemData)
	if block == nil {
		log.Fatalf("bad key data: %s", "not PEM-encoded")
	}
	if got, want := block.Type, "RSA PRIVATE KEY"; got != want {
		log.Fatalf("unknown key type %q, want %q", got, want)
	}

	// Decode the RSA private key
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		log.Fatalf("bad private key: %s", err)
	}

	label := []byte("orders")
	var out []byte
	if *decrypt {
		// Decrypt the data
		out, err = rsa.DecryptOAEP(sha256.New(), rand.Reader, priv, in, label)
		if err != nil {
			log.Fatalf("decrypt: %s", err)
		}
	} else {
		out, err = rsa.EncryptOAEP(sha256.New(), rand.Reader, &priv.PublicKey, in, label)
		if err != nil {
			log.Fatalf("encrypt: %s", err)
		}
		//fmt.Println(priv.PublicKey)
		//fmt.Println(priv)
	}

	// Write data to output file
	if err := ioutil.WriteFile(*outFile, out, 0600); err != nil {
		log.Fatalf("write output: %s", err)
	}
}
Beispiel #25
0
func (alg *RsaOaep) WrapNewKey(cekSizeBits int, key interface{}, header map[string]interface{}) (cek []byte, encryptedCek []byte, err error) {
	if pubKey, ok := key.(*rsa.PublicKey); ok {
		if cek, err = arrays.Random(cekSizeBits >> 3); err == nil {
			encryptedCek, err = rsa.EncryptOAEP(alg.sha(), rand.Reader, pubKey, cek, nil)
			return
		}

		return nil, nil, err
	}

	return nil, nil, errors.New("RsaOaep.WrapNewKey(): expected key to be '*rsa.PublicKey'")
}
Beispiel #26
0
// Encrypt signs the message with the private key, and encrypts it to
// the certificate supplied.
func Encrypt(priv *rsa.PrivateKey, cert *x509.Certificate, msg []byte) ([]byte, bool) {
	var pub *rsa.PublicKey
	switch certPub := cert.PublicKey.(type) {
	case *rsa.PublicKey:
		pub = certPub
	default:
		return nil, false
	}

	var signed = signature{msg, nil}

	h := sha256.New()
	h.Write(msg)

	var err error
	signed.Signature, err = rsa.SignPSS(rand.Reader, priv, crypto.SHA256,
		h.Sum(nil), nil)
	if err != nil {
		return nil, false
	}

	out, err := asn1.Marshal(signed)
	if err != nil {
		return nil, false
	}

	key := aesgcm.NewKey()
	if key == nil {
		return nil, false
	}

	out, ok := aesgcm.Encrypt(key, out)
	if !ok {
		return nil, false
	}

	var message message
	message.Signed = out

	h.Reset()
	message.Key, err = rsa.EncryptOAEP(h, rand.Reader, pub, key, nil)
	if err != nil {
		return nil, false
	}

	out, err = asn1.Marshal(message)
	if err != nil {
		return nil, false
	}

	return out, true
}
Beispiel #27
0
func EncryptMessage(msg []byte, pbkey *rsa.PublicKey) []byte {
	sha1hash := sha1.New()
	var encrypted_packets [][]byte
	var msg_len int = len(msg)
	var packet_size int = 32
	var full_packets int = msg_len / packet_size
	var remainder int = msg_len - (msg_len/packet_size)*packet_size

	var total_bytes uint32
	if remainder > 0 {
		total_bytes = uint32((full_packets + 1) * key_len / 8)
	} else {
		total_bytes = uint32(full_packets * key_len / 8)
	}

	total_bytes_bytes := make([]byte, 4)
	binary.LittleEndian.PutUint32(total_bytes_bytes, total_bytes)
	packet, err := rsa.EncryptOAEP(sha1hash, rand.Reader, pbkey, total_bytes_bytes, nil)
	encrypted_packets = append(encrypted_packets, packet)
	// fmt.Printf("OAEP encrypted [%d] to \n[%x]\n", total_bytes, packet)
	for packet_num := 0; packet_num < full_packets; packet_num++ {
		// fmt.Printf("OAEP encrypting [%s]...\n", string(msg[packet_size*packet_num:packet_size*(packet_num+1)]))
		packet, err := rsa.EncryptOAEP(sha1hash, rand.Reader, pbkey, msg[packet_size*packet_num:packet_size*(packet_num+1)], nil)
		if err != nil {
			log.Fatal("(EncryptMessage) Encrypt Packet: ", err)
		} else {
			// fmt.Printf("...to [%x]\n", packet)
			encrypted_packets = append(encrypted_packets, packet)
		}
	}
	packet, err = rsa.EncryptOAEP(sha1hash, rand.Reader, pbkey, msg[packet_size*full_packets:], nil)
	if err != nil {
		log.Fatal("(EncryptMessage) Encrypt Remainder: ", err)
	} else {
		// fmt.Printf("OAEP encrypted [%s] to \n[%x]\n", string(msg[packet_size*full_packets:]), packet)
		encrypted_packets = append(encrypted_packets, packet)
	}
	return bytes.Join(encrypted_packets, nil)
}
// Encrypt plaintext with RSA public key.
func encryptWithPublicKey(plaintext, publicKey []byte) ([]byte, error) {
	parsedKey, err := x509.ParsePKIXPublicKey(publicKey)
	if err != nil {
		return nil, common.ContextError(err)
	}
	if rsaPubKey, ok := parsedKey.(*rsa.PublicKey); ok {
		rsaEncryptOutput, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, rsaPubKey, plaintext, nil)
		if err != nil {
			return nil, common.ContextError(err)
		}
		return rsaEncryptOutput, nil
	}
	return nil, common.ContextError(errors.New("feedback key is not an RSA public key"))
}
/**
 *
 *
 *
 * @return
 */
func Encrypt(data interface{}) ([]byte, error) {

	var privateKey *rsa.PrivateKey
	privateKey, err := readRSAKey()
	CheckError(err)
	dataBytes, err := json.Marshal(data)
	CheckError(err)

	cipherBytes, err := rsa.EncryptOAEP(
		sha256.New(), rand.Reader, &privateKey.PublicKey, dataBytes, nil)

	return cipherBytes, err
	return dataBytes, err
}
// Function check if private key could decode what public key encode
func authorize(pubkey *rsa.PublicKey, privkey_str []byte) (bool, error) {
	block, _ := pem.Decode(privkey_str)
	if block == nil {
		return false, errors.New("Provided data is not private key")
	}
	if len(block.Bytes) < 100 {
		return false, errors.New("Provided data is not private key")
	}

	privkey := new(rsa.PrivateKey)

	if block.Type == "RSA PRIVATE KEY" {

		privkey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)

	} else {
		return false, errors.New("Provided data is not private key")
	}

	// Encrypt message
	eComm, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, pubkey, []byte(testMessage), nil)
	if err != nil {
		return false, err
	}

	log.Println("Encrypted data " + string(eComm[:]))
	log.Println(eComm[:])
	test := []byte{
		75, 171, 179, 168, 150, 13, 169, 80, 26, 131, 139, 152, 174, 42, 69, 237, 56, 148, 43, 29, 48, 179, 116, 109, 226, 86, 102, 236, 225, 150, 192, 52, 96, 6, 203, 147, 106, 50, 228, 117, 89, 220, 214, 2, 156, 53, 86, 236, 73, 167, 186, 30, 27, 140, 67, 181, 65, 176, 95, 115, 189, 99, 72, 219, 88, 158, 242, 101, 78, 244, 137, 80, 150, 26, 20, 163, 190, 26, 165, 45, 82, 228, 140, 100, 116, 210, 63, 247, 103, 14, 131, 22, 172, 128, 171, 121, 13, 218, 2, 217, 119, 51, 243, 39, 22, 49, 165, 4, 204, 248, 251, 129, 190, 153, 27, 170, 56, 83, 108, 87, 56, 187, 88, 9, 119, 35, 247, 125,
	}

	msg1, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privkey, test, nil)

	log.Println(string(msg1))

	// Decrypt message
	msg, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privkey, eComm, nil)
	if err != nil {
		return false, err
	}

	// If Decrypted message euqal with original - private key is correct and user authorized

	if string(msg) == testMessage {
		return true, nil
	}

	return false, nil
}