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 case CRYPTO_RSA3072: 27 return 3072; 28 case CRYPTO_RSA4096: 29 return 4096; 30 } 31 32 printf("Unknown crypto algorithm: 0x%x\n", algo); 33 34 return 0; 35 } 36 37 struct udevice *crypto_get_device(u32 capability) 38 { 39 const struct dm_crypto_ops *ops; 40 struct udevice *dev; 41 struct uclass *uc; 42 int ret; 43 u32 cap; 44 45 ret = uclass_get(UCLASS_CRYPTO, &uc); 46 if (ret) 47 return NULL; 48 49 for (uclass_first_device(UCLASS_CRYPTO, &dev); 50 dev; 51 uclass_next_device(&dev)) { 52 ops = device_get_ops(dev); 53 if (!ops || !ops->capability) 54 continue; 55 56 cap = ops->capability(dev); 57 if ((cap & capability) == capability) 58 return dev; 59 } 60 61 return NULL; 62 } 63 64 int crypto_sha_init(struct udevice *dev, sha_context *ctx) 65 { 66 const struct dm_crypto_ops *ops = device_get_ops(dev); 67 68 if (!ops || !ops->sha_init) 69 return -ENOSYS; 70 71 return ops->sha_init(dev, ctx); 72 } 73 74 int crypto_sha_update(struct udevice *dev, u32 *input, u32 len) 75 { 76 const struct dm_crypto_ops *ops = device_get_ops(dev); 77 78 if (!ops || !ops->sha_update) 79 return -ENOSYS; 80 81 return ops->sha_update(dev, input, len); 82 } 83 84 int crypto_sha_final(struct udevice *dev, sha_context *ctx, u8 *output) 85 { 86 const struct dm_crypto_ops *ops = device_get_ops(dev); 87 88 if (!ops || !ops->sha_final) 89 return -ENOSYS; 90 91 return ops->sha_final(dev, ctx, output); 92 } 93 94 int crypto_sha_csum(struct udevice *dev, sha_context *ctx, 95 char *input, u32 input_len, u8 *output) 96 { 97 int ret; 98 99 ret = crypto_sha_init(dev, ctx); 100 if (ret) 101 return ret; 102 103 ret = crypto_sha_update(dev, (u32 *)input, input_len); 104 if (ret) 105 return ret; 106 107 ret = crypto_sha_final(dev, ctx, output); 108 109 return ret; 110 } 111 112 int crypto_rsa_verify(struct udevice *dev, rsa_key *ctx, u8 *sign, u8 *output) 113 { 114 const struct dm_crypto_ops *ops = device_get_ops(dev); 115 116 if (!ops || !ops->rsa_verify) 117 return -ENOSYS; 118 119 return ops->rsa_verify(dev, ctx, sign, output); 120 } 121 122 UCLASS_DRIVER(crypto) = { 123 .id = UCLASS_CRYPTO, 124 .name = "crypto", 125 }; 126