Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AES-CFB Cipher support #32

Open
murugesanp opened this issue Aug 17, 2023 · 0 comments
Open

Add AES-CFB Cipher support #32

murugesanp opened this issue Aug 17, 2023 · 0 comments

Comments

@murugesanp
Copy link

murugesanp commented Aug 17, 2023

Couldn't able to parse password encrypted aes-256-cfb pkcs8 private keys. The library throws the below error,
pkcs8: unsupported cipher (OID: 2.16.840.1.101.3.4.1.44)
Can you please add the support for this?

var oidAES256CFB = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 44}

var AES256CFB = cipherWithBlock{
	ivSize:   aes.BlockSize,
	keySize:  32,
	newBlock: aes.NewCipher,
	oid:      oidAES256CFB,
}

func init() {
	RegisterCipher(oidAES256CFB, func() Cipher {
		return AES256CFB
	})
}

type cipherWithBlock struct {
	oid      asn1.ObjectIdentifier
	ivSize   int
	keySize  int
	newBlock func(key []byte) (cipher.Block, error)
}

func (c cipherWithBlock) IVSize() int {
	return c.ivSize
}

func (c cipherWithBlock) KeySize() int {
	return c.keySize
}

func (c cipherWithBlock) OID() asn1.ObjectIdentifier {
	return c.oid
}

func (c cipherWithBlock) Encrypt(key, iv, plaintext []byte) ([]byte, error) {
	block, err := c.newBlock(key)
	if err != nil {
		return nil, err
	}
	return cfbEncrypt(block, key, iv, plaintext)
}

func (c cipherWithBlock) Decrypt(key, iv, ciphertext []byte) ([]byte, error) {
	block, err := c.newBlock(key)
	if err != nil {
		return nil, err
	}
	return cfbDecrypt(block, key, iv, ciphertext)
}

func cfbEncrypt(block cipher.Block, key, iv, plaintext []byte) ([]byte, error) {
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
	return ciphertext, nil
}

func cfbDecrypt(block cipher.Block, key, iv, ciphertext []byte) ([]byte, error) {
	stream := cipher.NewCFBDecrypter(block, iv)
	plaintext := make([]byte, len(ciphertext))
	stream.XORKeyStream(plaintext, ciphertext)
	return plaintext, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant