Skip to content

Commit dd7f0c7

Browse files
committed
Add test for encryption service
1 parent 88c20ad commit dd7f0c7

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import RsaEncryptionService from '../../src/features/encrypt/EncryptionService'
2+
import { generateKeyPairSync } from 'crypto'
3+
4+
describe('RsaEncryptionService', () => {
5+
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
6+
modulusLength: 2048,
7+
publicKeyEncoding: {
8+
type: 'spki',
9+
format: 'pem'
10+
},
11+
privateKeyEncoding: {
12+
type: 'pkcs8',
13+
format: 'pem'
14+
}
15+
})
16+
17+
const encryptionService = new RsaEncryptionService({ publicKey, privateKey })
18+
19+
it('should encrypt and decrypt data correctly', () => {
20+
const data = 'Hello, World!'
21+
const encryptedData = encryptionService.encrypt(data)
22+
const decryptedData = encryptionService.decrypt(encryptedData)
23+
24+
expect(decryptedData).toBe(data)
25+
})
26+
27+
it('should throw an error when decrypting with incorrect data', () => {
28+
const incorrectData = 'invalidEncryptedData'
29+
30+
expect(() => {
31+
encryptionService.decrypt(incorrectData)
32+
}).toThrow()
33+
})
34+
35+
it('should throw an error when encrypting with an invalid public key', () => {
36+
const invalidPublicKey = 'invalidPublicKey'
37+
const invalidEncryptionService = new RsaEncryptionService({ publicKey: invalidPublicKey, privateKey })
38+
39+
expect(() => {
40+
invalidEncryptionService.encrypt('test')
41+
}).toThrow()
42+
})
43+
44+
it('should throw an error when decrypting with an invalid private key', () => {
45+
const data = 'Hello, World!'
46+
const encryptedData = encryptionService.encrypt(data)
47+
const invalidPrivateKey = 'invalidPrivateKey'
48+
const invalidEncryptionService = new RsaEncryptionService({ publicKey, privateKey: invalidPrivateKey })
49+
50+
expect(() => {
51+
invalidEncryptionService.decrypt(encryptedData)
52+
}).toThrow()
53+
})
54+
})

0 commit comments

Comments
 (0)