pkcs8 icon indicating copy to clipboard operation
pkcs8 copied to clipboard

Add AES-CFB Cipher support

Open murugesanp opened this issue 1 year ago • 0 comments

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
}

murugesanp avatar Aug 17 '23 08:08 murugesanp