xref: /rk3399_rockchip-uboot/drivers/crypto/crypto-uclass.c (revision ff294bc6d1de6dc409baee2690a1a7da5f92127e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2019 Fuzhou Rockchip Electronics Co., Ltd
4  */
5 
6 #include <common.h>
7 #include <crypto.h>
8 #include <dm.h>
9 #include <u-boot/sha1.h>
10 
11 u32 crypto_algo_nbits(u32 algo)
12 {
13 	switch (algo) {
14 	case CRYPTO_MD5:
15 		return 128;
16 	case CRYPTO_SHA1:
17 		return 160;
18 	case CRYPTO_SHA256:
19 		return 256;
20 	case CRYPTO_RSA512:
21 		return 512;
22 	case CRYPTO_RSA1024:
23 		return 1024;
24 	case CRYPTO_RSA2048:
25 		return 2048;
26 	}
27 
28 	printf("Unknown crypto algorithm: 0x%x\n", algo);
29 
30 	return 0;
31 }
32 
33 struct udevice *crypto_get_device(u32 capability)
34 {
35 	const struct dm_crypto_ops *ops;
36 	struct udevice *dev;
37 	struct uclass *uc;
38 	int ret;
39 	u32 cap;
40 
41 	ret = uclass_get(UCLASS_CRYPTO, &uc);
42 	if (ret)
43 		return NULL;
44 
45 	for (uclass_first_device(UCLASS_CRYPTO, &dev);
46 	     dev;
47 	     uclass_next_device(&dev)) {
48 		ops = device_get_ops(dev);
49 		if (!ops || !ops->capability)
50 			continue;
51 
52 		cap = ops->capability(dev);
53 		if ((cap & capability) == capability)
54 			return dev;
55 	}
56 
57 	return NULL;
58 }
59 
60 int crypto_sha_init(struct udevice *dev, sha_context *ctx)
61 {
62 	const struct dm_crypto_ops *ops = device_get_ops(dev);
63 
64 	if (!ops || !ops->sha_init)
65 		return -ENOSYS;
66 
67 	return ops->sha_init(dev, ctx);
68 }
69 
70 int crypto_sha_update(struct udevice *dev, u32 *input, u32 len)
71 {
72 	const struct dm_crypto_ops *ops = device_get_ops(dev);
73 
74 	if (!ops || !ops->sha_update)
75 		return -ENOSYS;
76 
77 	return ops->sha_update(dev, input, len);
78 }
79 
80 int crypto_sha_final(struct udevice *dev, sha_context *ctx, u8 *output)
81 {
82 	const struct dm_crypto_ops *ops = device_get_ops(dev);
83 
84 	if (!ops || !ops->sha_final)
85 		return -ENOSYS;
86 
87 	return ops->sha_final(dev, ctx, output);
88 }
89 
90 int crypto_sha_csum(struct udevice *dev, sha_context *ctx,
91 		    char *input, u32 input_len, u8 *output)
92 {
93 	int ret;
94 
95 	ret = crypto_sha_init(dev, ctx);
96 	if (ret)
97 		return ret;
98 
99 	ret = crypto_sha_update(dev, (u32 *)input, input_len);
100 	if (ret)
101 		return ret;
102 
103 	ret = crypto_sha_final(dev, ctx, output);
104 
105 	return ret;
106 }
107 
108 int crypto_rsa_verify(struct udevice *dev, rsa_key *ctx, u8 *sign, u8 *output)
109 {
110 	const struct dm_crypto_ops *ops = device_get_ops(dev);
111 
112 	if (!ops || !ops->rsa_verify)
113 		return -ENOSYS;
114 
115 	return ops->rsa_verify(dev, ctx, sign, output);
116 }
117 
118 UCLASS_DRIVER(crypto) = {
119 	.id	= UCLASS_CRYPTO,
120 	.name	= "crypto",
121 };
122